Skip to main content

factorion_lib/
calculation_tasks.rs

1//! This module handles the calculation of pending calculation tasks
2
3use factorion_math::rug::ops::AddFrom;
4#[cfg(any(feature = "serde", test))]
5use serde::{Deserialize, Serialize};
6
7use crate::calculation_results::Number;
8
9use crate::Consts;
10use crate::{
11    calculation_results::{Calculation, CalculationResult},
12    math,
13};
14
15use crate::rug::{Float, ops::Pow};
16
17pub mod recommended {
18    use factorion_math::rug::Complete;
19    use factorion_math::rug::integer::IntegerExt64;
20
21    use crate::rug::Integer;
22    // Limit for exact calculation, set to limit calculation time
23    pub static UPPER_CALCULATION_LIMIT: fn() -> Integer = || 1_000_000.into();
24    // Limit for approximation, set to ensure enough accuracy (5 decimals)
25    pub static UPPER_APPROXIMATION_LIMIT: fn() -> Integer =
26        || Integer::u64_pow_u64(10, 300).complete();
27    // Limit for exact subfactorial calculation, set to limit calculation time
28    pub static UPPER_SUBFACTORIAL_LIMIT: fn() -> Integer = || 100_000.into();
29    // Limit for exact termial calculation, set to limit calculation time (absurdly high)
30    pub static UPPER_TERMIAL_LIMIT: fn() -> Integer = || Integer::u64_pow_u64(10, 10000).complete();
31    // Limit for approximation, set to ensure enough accuracy (5 decimals)
32    // Based on max float. (bits)
33    pub static UPPER_TERMIAL_APPROXIMATION_LIMIT: u32 = 1073741822;
34}
35
36/// Representation of the calculation to be done
37#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
38#[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))]
39pub struct CalculationJob {
40    pub base: CalculationBase,
41    /// Type of the calculation
42    pub level: i32,
43    /// Number of negations encountered
44    pub negative: u32,
45}
46/// The basis of a calculation, whether [Number] or [CalculationJob].
47#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
48#[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))]
49pub enum CalculationBase {
50    Num(Number),
51    Calc(Box<CalculationJob>),
52}
53
54impl CalculationJob {
55    /// Execute the calculation. \
56    /// If include_steps is enabled, will return all intermediate results.
57    pub fn execute(self, include_steps: bool, consts: &Consts) -> Vec<Option<Calculation>> {
58        let CalculationJob {
59            mut base,
60            mut level,
61            mut negative,
62        } = self;
63        let size = {
64            let mut n = 1;
65            let mut b = &base;
66            while let CalculationBase::Calc(inner) = b {
67                n += 1;
68                b = &inner.base;
69            }
70            n
71        };
72        // TODO: Maybe ignore include steps if size is too big (we can't respond properly anyway)
73        let mut steps = Vec::with_capacity(size);
74        let mut calcs = loop {
75            match base {
76                CalculationBase::Num(num) => {
77                    break vec![
78                        Self::calculate_appropriate_factorial(num.clone(), level, negative, consts)
79                            .map(|res| Calculation {
80                                value: num,
81                                steps: vec![(level, negative % 2 == 1)],
82                                result: res,
83                            }),
84                    ];
85                }
86                CalculationBase::Calc(calc) => {
87                    steps.push((level, negative));
88                    CalculationJob {
89                        base,
90                        level,
91                        negative,
92                    } = *calc;
93                }
94            }
95        };
96        for (i, (level, negative)) in steps.into_iter().rev().enumerate() {
97            let calc = if include_steps && i < 30 {
98                calcs.last().cloned()
99            } else {
100                calcs.pop()
101            };
102            match calc {
103                Some(Some(Calculation {
104                    result: res,
105                    mut steps,
106                    value: number,
107                })) => {
108                    let factorial = Self::calculate_appropriate_factorial(
109                        res, level, negative, consts,
110                    )
111                    .map(|res| {
112                        steps.push((level, negative % 2 == 1));
113                        Calculation {
114                            value: number,
115                            steps,
116                            result: res,
117                        }
118                    });
119                    calcs.push(factorial);
120                }
121                _ => return calcs,
122            };
123        }
124        calcs
125    }
126    fn calculate_appropriate_factorial(
127        num: Number,
128        level: i32,
129        negative: u32,
130        consts: &Consts,
131    ) -> Option<CalculationResult> {
132        let prec = consts.float_precision;
133        let calc_num = match num {
134            CalculationResult::Approximate(base, exponent) => {
135                if exponent <= consts.integer_construction_limit {
136                    let x: Float = base.as_float() * Float::with_val(prec, 10).pow(&exponent);
137                    x.to_integer().unwrap()
138                } else {
139                    return Some(if base.as_float() < &0.0 {
140                        CalculationResult::ComplexInfinity
141                    } else if level < 0 {
142                        let termial = math::approximate_approx_termial(
143                            (Float::from(base), exponent),
144                            -level as u32,
145                        );
146                        if termial.0 == 1 {
147                            CalculationResult::ApproximateDigits(false, termial.1)
148                        } else {
149                            CalculationResult::Approximate(termial.0.into(), termial.1)
150                        }
151                    } else {
152                        let mut exponent = exponent;
153                        exponent.add_from(math::length(&exponent, prec));
154                        CalculationResult::ApproximateDigitsTower(false, false, 1.into(), exponent)
155                    });
156                }
157            }
158            CalculationResult::ApproximateDigits(was_neg, digits) => {
159                if digits <= consts.integer_construction_limit {
160                    let x: Float = Float::with_val(prec, 10).pow(digits.clone() - 1);
161                    x.to_integer().unwrap()
162                } else {
163                    return Some(if digits.is_negative() {
164                        CalculationResult::Float(Float::new(prec).into())
165                    } else if was_neg {
166                        CalculationResult::ComplexInfinity
167                    } else if level < 0 {
168                        let mut one = Float::with_val(consts.float_precision, 1);
169                        if was_neg {
170                            one *= -1;
171                        }
172                        let termial =
173                            math::approximate_approx_termial((one, digits), -level as u32);
174                        if termial.0 == 1 {
175                            CalculationResult::ApproximateDigits(false, termial.1)
176                        } else {
177                            CalculationResult::Approximate(termial.0.into(), termial.1)
178                        }
179                    } else {
180                        let mut digits = digits;
181                        digits.add_from(math::length(&digits, prec));
182                        CalculationResult::ApproximateDigitsTower(false, false, 1.into(), digits)
183                    });
184                }
185            }
186            CalculationResult::ApproximateDigitsTower(was_neg, neg, depth, exponent) => {
187                return Some(if neg {
188                    CalculationResult::Float(Float::new(prec).into())
189                } else if was_neg {
190                    CalculationResult::ComplexInfinity
191                } else if level < 0 {
192                    CalculationResult::ApproximateDigitsTower(false, false, depth, exponent)
193                } else {
194                    CalculationResult::ApproximateDigitsTower(false, false, depth + 1, exponent)
195                });
196            }
197            CalculationResult::ComplexInfinity => return Some(CalculationResult::ComplexInfinity),
198            Number::Float(num) => match level {
199                ..-1 => {
200                    // We don't support multitermials of decimals
201                    return None;
202                }
203                -1 => {
204                    let res: Float = math::fractional_termial(num.as_float().clone())
205                        * if !negative.is_multiple_of(2) { -1 } else { 1 };
206                    if res.is_finite() {
207                        return Some(CalculationResult::Float(res.into()));
208                    } else {
209                        num.as_float().to_integer()?
210                    }
211                }
212                0 => {
213                    // We don't support subfactorials of deciamals
214                    return None;
215                }
216                1 => {
217                    let res: Float = math::fractional_factorial(num.as_float().clone())
218                        * if !negative.is_multiple_of(2) { -1 } else { 1 };
219                    if res.is_finite() {
220                        return Some(CalculationResult::Float(res.into()));
221                    } else {
222                        num.as_float().to_integer()?
223                    }
224                }
225                2.. => {
226                    let res: Float =
227                        math::fractional_multifactorial(num.as_float().clone(), level as u32)
228                            * if !negative.is_multiple_of(2) { -1 } else { 1 };
229                    if res.is_finite() {
230                        return Some(CalculationResult::Float(res.into()));
231                    } else {
232                        num.as_float().to_integer()?
233                    }
234                }
235            },
236            Number::Exact(num) => num,
237        };
238        if level > 0 {
239            Some(if calc_num < 0 && level == 1 {
240                CalculationResult::ComplexInfinity
241            } else if calc_num < 0 {
242                let factor = math::negative_multifacorial_factor(calc_num.clone(), level);
243                match (factor, -level - 1 > calc_num) {
244                    (Some(factor), true) => {
245                        let mut res = Self::calculate_appropriate_factorial(
246                            Number::Exact(-calc_num.clone() - level),
247                            level,
248                            negative,
249                            consts,
250                        )?;
251                        res = match res {
252                            CalculationResult::Exact(n) => {
253                                let n = Float::with_val(prec, n);
254                                CalculationResult::Float((factor / n).into())
255                            }
256                            CalculationResult::Approximate(b, e) => {
257                                let (b, e) =
258                                    math::adjust_approximate((factor / Float::from(b), -e));
259                                CalculationResult::Approximate(b.into(), e)
260                            }
261                            CalculationResult::ApproximateDigits(wn, n) => {
262                                CalculationResult::ApproximateDigits(wn, -n)
263                            }
264                            CalculationResult::ApproximateDigitsTower(
265                                wn,
266                                negative,
267                                depth,
268                                base,
269                            ) => CalculationResult::ApproximateDigitsTower(
270                                wn, !negative, depth, base,
271                            ),
272                            CalculationResult::ComplexInfinity => {
273                                CalculationResult::Exact(0.into())
274                            }
275                            CalculationResult::Float(f) => {
276                                CalculationResult::Float((factor / Float::from(f)).into())
277                            }
278                        };
279
280                        res
281                    }
282                    (factor, _) => factor
283                        .map(CalculationResult::Exact)
284                        .unwrap_or(CalculationResult::ComplexInfinity),
285                }
286                // Check if we can approximate the number of digits
287            } else if calc_num > consts.upper_approximation_limit {
288                let factorial =
289                    math::approximate_multifactorial_digits(calc_num.clone(), level as u32, prec);
290                CalculationResult::ApproximateDigits(!negative.is_multiple_of(2), factorial)
291            // Check if the number is within a reasonable range to compute
292            } else if calc_num > consts.upper_calculation_limit {
293                let factorial = if level == 0 {
294                    math::approximate_factorial(calc_num.clone(), prec)
295                } else {
296                    math::approximate_multifactorial(calc_num.clone(), level as u32, prec)
297                };
298                CalculationResult::Approximate(
299                    ((factorial.0 * if !negative.is_multiple_of(2) { -1 } else { 1 }) as Float)
300                        .into(),
301                    factorial.1,
302                )
303            } else {
304                let calc_num = calc_num
305                    .to_u64()
306                    .unwrap_or_else(|| panic!("Failed to convert BigInt to u64: {calc_num}"));
307                let factorial = math::factorial(calc_num, level as u32)
308                    * if !negative.is_multiple_of(2) { -1 } else { 1 };
309                CalculationResult::Exact(factorial)
310            })
311        } else if level == 0 {
312            Some(if calc_num < 0 {
313                CalculationResult::ComplexInfinity
314            } else if calc_num > consts.upper_approximation_limit {
315                let factorial = math::approximate_multifactorial_digits(calc_num.clone(), 1, prec);
316                CalculationResult::ApproximateDigits(!negative.is_multiple_of(2), factorial)
317            } else if calc_num > consts.upper_subfactorial_limit {
318                let factorial = math::approximate_subfactorial(calc_num.clone(), prec);
319                CalculationResult::Approximate(
320                    ((factorial.0 * if !negative.is_multiple_of(2) { -1 } else { 1 }) as Float)
321                        .into(),
322                    factorial.1,
323                )
324            } else {
325                let calc_num = calc_num
326                    .to_u64()
327                    .unwrap_or_else(|| panic!("Failed to convert BigInt to u64: {calc_num}"));
328                let factorial =
329                    math::subfactorial(calc_num) * if !negative.is_multiple_of(2) { -1 } else { 1 };
330                CalculationResult::Exact(factorial)
331            })
332        } else if level < 0 {
333            Some(
334                if calc_num.significant_bits() > consts.upper_termial_approximation_limit {
335                    let termial = math::approximate_termial_digits(calc_num, -level as u32, prec);
336                    CalculationResult::ApproximateDigits(!negative.is_multiple_of(2), termial)
337                } else if calc_num > consts.upper_termial_limit {
338                    let termial = math::approximate_termial(calc_num, -level as u32, prec);
339                    CalculationResult::Approximate(
340                        ((termial.0 * if !negative.is_multiple_of(2) { -1 } else { 1 }) as Float)
341                            .into(),
342                        termial.1,
343                    )
344                } else {
345                    let termial = if level < -1 {
346                        math::multitermial(calc_num, -level as u32)
347                    } else {
348                        math::termial(calc_num)
349                    };
350                    let termial = termial * if !negative.is_multiple_of(2) { -1 } else { 1 };
351                    CalculationResult::Exact(termial)
352                },
353            )
354        } else {
355            unreachable!()
356        }
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    use super::*;
363    use factorion_math::recommended::FLOAT_PRECISION;
364
365    #[test]
366    fn test_unsupported_calcs() {
367        let consts = Consts::default();
368        // Subfactorial
369        let job = CalculationJob {
370            base: CalculationBase::Num(Number::Float(Float::with_val(FLOAT_PRECISION, 1.5).into())),
371            level: 0,
372            negative: 0,
373        };
374        assert_eq!(job.execute(false, &consts), vec![None]);
375        // Multitermial
376        let job = CalculationJob {
377            base: CalculationBase::Num(Number::Float(Float::with_val(FLOAT_PRECISION, 1.5).into())),
378            level: -2,
379            negative: 0,
380        };
381        assert_eq!(job.execute(false, &consts), vec![None]);
382        let job = CalculationJob {
383            base: CalculationBase::Num(Number::Float(Float::with_val(FLOAT_PRECISION, 1.5).into())),
384            level: -51,
385            negative: 0,
386        };
387        assert_eq!(job.execute(false, &consts), vec![None]);
388    }
389}