ctb_formats_pan/
math.rs

1/* SPDX-License-Identifier: MIT */
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7Permission is hereby granted, free of charge, to any person obtaining a copy of
8this software and associated documentation files (the “Software”), to deal in
9the Software without restriction, including without limitation the rights to
10use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11the Software, and to permit persons to whom the Software is furnished to do so,
12subject to the following conditions:
13
14The above copyright notice and this permission notice shall be included in all
15copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23SOFTWARE.
24*/
25
26//! Pan math and numeric helpers.
27
28#[allow(
29    unused_imports,
30    clippy::wildcard_imports,
31    reason = "Standard workspace module prelude"
32)]
33use crate::utilities::*;
34use ctb_utilities::math::exact_float::{f64_to_u64, u64_to_f64_exact};
35use malachite::Natural;
36
37/// Returns the absolute value of `number`.
38pub fn abs(number: f64) -> f64 {
39    number.abs()
40}
41
42/// Adds two numbers.
43/// This will not match proper Pan math, which uses either ints/fixed point (I think both of those might wrap on overflow?) or floats (which I think are 32-bit).
44#[expect(
45    clippy::arithmetic_side_effects,
46    reason = "standard operators are saturating with floats I think"
47)]
48pub fn add(numerator: f64, denominator: f64) -> f64 {
49    numerator + denominator
50}
51
52/// Subtracts `denominator` from `numerator`.
53#[expect(
54    clippy::arithmetic_side_effects,
55    reason = "standard operators are saturating with floats I think"
56)]
57pub fn sub(numerator: f64, denominator: f64) -> f64 {
58    numerator - denominator
59}
60
61/// Multiplies two numbers.
62#[expect(
63    clippy::arithmetic_side_effects,
64    reason = "standard operators are saturating with floats I think"
65)]
66pub fn mul(numerator: f64, denominator: f64) -> f64 {
67    numerator * denominator
68}
69
70/// Divides `numerator` by `denominator`.
71#[expect(
72    clippy::arithmetic_side_effects,
73    reason = "standard operators are saturating with floats I think"
74)]
75pub fn div(numerator: f64, denominator: f64) -> f64 {
76    numerator / denominator
77}
78
79/// Divides, returning 0 when `denominator` is zero.
80#[expect(
81    clippy::arithmetic_side_effects,
82    reason = "standard operators are saturating with floats I think"
83)]
84pub fn divzero(numerator: f64, denominator: f64) -> f64 {
85    if denominator == 0.0 {
86        0.0
87    } else {
88        numerator / denominator
89    }
90}
91
92/// Truncates `number` toward zero.
93pub fn fix(number: f64) -> Result<f64> {
94    Ok(number.trunc())
95}
96
97/// Floors `number` to the nearest integer toward $-\infty$.
98pub fn int(number: f64) -> Result<f64> {
99    Ok(number.floor())
100}
101
102/// In theory, convert to fixed point. At the moment this returns `number`
103/// unchanged.
104pub fn fixed(number: f64) -> Result<f64> {
105    Ok(number)
106}
107
108/// In theory, converts to floating point. At the moment this returns `number`
109/// unchanged.
110pub fn float(number: f64) -> Result<f64> {
111    Ok(number)
112}
113
114/// Returns the larger of `a` and `b`.
115pub fn max(a: f64, b: f64) -> f64 {
116    a.max(b)
117}
118
119/// Returns the smaller of `a` and `b`.
120pub fn min(a: f64, b: f64) -> f64 {
121    a.min(b)
122}
123
124/// Adds `extra` unless `value` is zero.
125pub fn numsandwich(value: f64, extra: f64) -> f64 {
126    if value == 0.0 { 0.0 } else { value + extra }
127}
128
129/// Rounds `number` to the nearest multiple of `step`.
130pub fn round(number: f64, step: f64) -> Result<f64> {
131    if !step.is_finite() || step == 0.0 {
132        bail!("round(): step must be finite and non-zero");
133    }
134    if !number.is_finite() {
135        return Ok(number);
136    }
137
138    let step = step.abs();
139    let q = number / step;
140    Ok(q.round() * step)
141}
142
143#[derive(Debug, Clone)]
144/// A small deterministic RNG (not cryptographically secure).
145pub struct PanRng {
146    state: u64,
147}
148
149impl PanRng {
150    /// Creates a new RNG with the given `seed`.
151    pub fn new(seed: u64) -> Self {
152        Self { state: seed }
153    }
154
155    fn next_u64(&mut self) -> u64 {
156        // xorshift64* (small, fast, deterministic). Not crypto-safe.
157        let mut x = self.state;
158        x ^= x >> 12;
159        x ^= x << 25;
160        x ^= x >> 27;
161        self.state = x;
162        x.wrapping_mul(2685821657736338717)
163    }
164
165    /// Returns a deterministic value in the range $[0, 1)$.
166    ///
167    /// This RNG is not cryptographically secure.
168    pub fn rnd(&mut self) -> Result<f64> {
169        // Map the top 53 bits to an f64 mantissa.
170        let u = self.next_u64() >> 11;
171        let denom = 9007199254740992.0_f64; // 2^53
172        let val = u64_to_f64_exact(u).context("Error converting u64 to f64")?;
173        Ok(val / denom)
174    }
175
176    /// Returns a deterministic integer in the inclusive range `start..=end`.
177    ///
178    /// This RNG is not cryptographically secure.
179    pub fn randominteger(&mut self, start: i64, end: i64) -> Result<i64> {
180        if start > end {
181            bail!("randominteger(): start must be <= end");
182        }
183        let span = end
184            .checked_sub(start)
185            .context("randominteger(): range overflow")?;
186        let span_u64 = u64::try_from(span)
187            .context("randominteger(): range must fit into u64")?;
188        let pick = if span_u64 == 0 {
189            0
190        } else {
191            self.next_u64()
192                .checked_rem(span_u64.saturating_add(1))
193                .context("randominteger(): range division error")?
194        };
195        let pick_i64 = i64::try_from(pick)
196            .context("randominteger(): pick must fit into i64")?;
197        start
198            .checked_add(pick_i64)
199            .context("randominteger(): result overflow")
200    }
201}
202
203/// Returns `None` when `number` is zero, otherwise `Some(number)`.
204pub fn zeroblank(number: f64) -> Option<f64> {
205    if number == 0.0 { None } else { Some(number) }
206}
207
208fn ensure_in_range_inclusive(
209    name: &str,
210    x: f64,
211    lo: f64,
212    hi: f64,
213) -> Result<()> {
214    if !x.is_finite() {
215        bail!("{name}(): input must be finite");
216    }
217    if x < lo || x > hi {
218        bail!("{name}(): input must be between {lo} and {hi}");
219    }
220    Ok(())
221}
222
223/// Returns $\arccos(number)$ for inputs in $[-1, 1]$.
224pub fn arccos(number: f64) -> Result<f64> {
225    ensure_in_range_inclusive("arccos", number, -1.0, 1.0)?;
226    Ok(number.acos())
227}
228
229/// Returns $\operatorname{arccosh}(number)$ for inputs $\ge 1$.
230pub fn arccosh(number: f64) -> Result<f64> {
231    if !number.is_finite() {
232        bail!("arccosh(): input must be finite");
233    }
234    if number < 1.0 {
235        bail!("arccosh(): input must be >= 1");
236    }
237    Ok(number.acosh())
238}
239
240/// Returns $\arcsin(number)$ for inputs in $[-1, 1]$.
241pub fn arcsin(number: f64) -> Result<f64> {
242    ensure_in_range_inclusive("arcsin", number, -1.0, 1.0)?;
243    Ok(number.asin())
244}
245
246/// Returns $\operatorname{arcsinh}(number)$.
247pub fn arcsinh(number: f64) -> Result<f64> {
248    if !number.is_finite() {
249        bail!("arcsinh(): input must be finite");
250    }
251    Ok(number.asinh())
252}
253
254/// Returns $\arctan(number)$.
255pub fn arctan(number: f64) -> Result<f64> {
256    if !number.is_finite() {
257        bail!("arctan(): input must be finite");
258    }
259    Ok(number.atan())
260}
261
262/// Returns $\operatorname{arctanh}(number)$ for inputs in $(-1, 1)$.
263pub fn arctanh(number: f64) -> Result<f64> {
264    if !number.is_finite() {
265        bail!("arctanh(): input must be finite");
266    }
267    if number <= -1.0 || number >= 1.0 {
268        bail!("arctanh(): input must be between -1 and +1 (exclusive)");
269    }
270    Ok(number.atanh())
271}
272
273/// Returns $\cos(number)$.
274pub fn cos(number: f64) -> Result<f64> {
275    if !number.is_finite() {
276        bail!("cos(): input must be finite");
277    }
278    Ok(number.cos())
279}
280
281/// Returns $\cosh(number)$.
282pub fn cosh(number: f64) -> Result<f64> {
283    if !number.is_finite() {
284        bail!("cosh(): input must be finite");
285    }
286    Ok(number.cosh())
287}
288
289/// Returns $e^{number}$.
290pub fn exp(number: f64) -> Result<f64> {
291    if !number.is_finite() {
292        bail!("exp(): input must be finite");
293    }
294    Ok(number.exp())
295}
296
297/// Returns the natural logarithm of `number`.
298pub fn log(number: f64) -> Result<f64> {
299    if !number.is_finite() {
300        bail!("log(): input must be finite");
301    }
302    if number <= 0.0 {
303        bail!("log(): input must be > 0");
304    }
305    Ok(number.ln())
306}
307
308/// Returns the base-10 logarithm of `number`.
309pub fn log10(number: f64) -> Result<f64> {
310    if !number.is_finite() {
311        bail!("log10(): input must be finite");
312    }
313    if number <= 0.0 {
314        bail!("log10(): input must be > 0");
315    }
316    Ok(number.log10())
317}
318
319/// Returns $\sin(number)$.
320pub fn sin(number: f64) -> Result<f64> {
321    if !number.is_finite() {
322        bail!("sin(): input must be finite");
323    }
324    Ok(number.sin())
325}
326
327/// Returns $\sinh(number)$.
328pub fn sinh(number: f64) -> Result<f64> {
329    if !number.is_finite() {
330        bail!("sinh(): input must be finite");
331    }
332    Ok(number.sinh())
333}
334
335/// Returns $\sqrt{number}$ for non-negative inputs.
336pub fn sqr(number: f64) -> Result<f64> {
337    if !number.is_finite() {
338        bail!("sqr(): input must be finite");
339    }
340    if number < 0.0 {
341        bail!("sqr(): input must be >= 0");
342    }
343    Ok(number.sqrt())
344}
345
346/// Returns $\tan(number)$.
347pub fn tan(number: f64) -> Result<f64> {
348    if !number.is_finite() {
349        bail!("tan(): input must be finite");
350    }
351    Ok(number.tan())
352}
353
354/// Returns $\tanh(number)$.
355pub fn tanh(number: f64) -> Result<f64> {
356    if !number.is_finite() {
357        bail!("tanh(): input must be finite");
358    }
359    Ok(number.tanh())
360}
361
362/// Returns the factorial of `number` as an $f64$.
363///
364/// The input must be an integer in the range 0..=170.
365pub fn fact(number: f64) -> Result<f64> {
366    if !number.is_finite() {
367        bail!("fact(): input must be finite");
368    }
369    if number < 0.0 {
370        bail!("fact(): input must be >= 0");
371    }
372    if number.fract() != 0.0 {
373        bail!("fact(): input must be an integer");
374    }
375
376    let n: u64 = f64_to_u64(number).context("fact(): input out of range")?;
377    if n > 170 {
378        bail!("fact(): input must be <= 170");
379    }
380
381    let mut acc = 1.0_f64;
382    let mut i = 2_u64;
383    while i <= n {
384        acc = <f64 as std::ops::Mul<f64>>::mul(acc, u64_to_f64_exact(i)?);
385        i = i
386            .checked_add(1)
387            .ok_or_else(|| anyhow::anyhow!("i overflowed"))?;
388    }
389    Ok(acc)
390}
391
392/// Returns the factorial of `n` as an exact big integer.
393pub fn fact_exact(n: u64) -> Result<Natural> {
394    let mut acc = Natural::from(1_u32);
395    let mut i = 2_u64;
396    while i <= n {
397        <Natural as std::ops::MulAssign<Natural>>::mul_assign(
398            &mut acc,
399            Natural::from(i),
400        );
401        i = i
402            .checked_add(1)
403            .ok_or_else(|| anyhow::anyhow!("i overflowed"))?;
404    }
405    Ok(acc)
406}
407
408fn validate_begin(begin: f64) -> Result<f64> {
409    if !begin.is_finite() {
410        bail!("begin must be finite");
411    }
412    if begin == 0.0 || begin == 1.0 {
413        Ok(begin)
414    } else {
415        bail!("begin must be 0 or 1");
416    }
417}
418
419/// Computes the payment for a loan or annuity.
420///
421/// `begin` must be 0 (end of period) or 1 (begin of period).
422pub fn pmt(
423    rate: f64,
424    periods: f64,
425    amount: f64,
426    fv: f64,
427    begin: f64,
428) -> Result<f64> {
429    if !rate.is_finite()
430        || !periods.is_finite()
431        || !amount.is_finite()
432        || !fv.is_finite()
433    {
434        bail!("pmt(): inputs must be finite");
435    }
436    let begin = validate_begin(begin)?;
437
438    if periods == 0.0 {
439        bail!("pmt(): periods must be non-zero");
440    }
441
442    if rate == 0.0 {
443        return Ok(-(amount + fv) / periods);
444    }
445
446    let one_plus_r = 1.0 + rate;
447    let pow = one_plus_r.powf(periods);
448    let annuity = (pow - 1.0) / rate;
449    let adj = 1.0 + rate * begin;
450    let denom = adj * annuity;
451    if denom == 0.0 {
452        bail!("pmt(): invalid parameters (division by zero)");
453    }
454
455    Ok(-(fv + amount * pow) / denom)
456}
457
458/// Computes the future value for a payment stream.
459///
460/// `begin` must be 0 (end of period) or 1 (begin of period).
461pub fn fv(
462    rate: f64,
463    periods: f64,
464    payment: f64,
465    pv: f64,
466    begin: f64,
467) -> Result<f64> {
468    if !rate.is_finite()
469        || !periods.is_finite()
470        || !payment.is_finite()
471        || !pv.is_finite()
472    {
473        bail!("fv(): inputs must be finite");
474    }
475    let begin = validate_begin(begin)?;
476
477    if rate == 0.0 {
478        return Ok(-(pv + payment * periods));
479    }
480
481    let one_plus_r = 1.0 + rate;
482    let pow = one_plus_r.powf(periods);
483    let annuity = (pow - 1.0) / rate;
484    let adj = 1.0 + rate * begin;
485
486    Ok(-(pv * pow + payment * adj * annuity))
487}
488
489/// Computes the present value for a payment stream.
490///
491/// `begin` must be 0 (end of period) or 1 (begin of period).
492pub fn pv(
493    rate: f64,
494    periods: f64,
495    payment: f64,
496    fv: f64,
497    begin: f64,
498) -> Result<f64> {
499    if !rate.is_finite()
500        || !periods.is_finite()
501        || !payment.is_finite()
502        || !fv.is_finite()
503    {
504        bail!("pv(): inputs must be finite");
505    }
506    let begin = validate_begin(begin)?;
507
508    if rate == 0.0 {
509        return Ok(-(payment * periods + fv));
510    }
511
512    let one_plus_r = 1.0 + rate;
513    let pow = one_plus_r.powf(periods);
514    let annuity = (pow - 1.0) / rate;
515    let adj = 1.0 + rate * begin;
516
517    Ok(-(fv + payment * adj * annuity) / pow)
518}
519
520#[cfg(test)]
521#[allow(
522    clippy::panic,
523    clippy::expect_used,
524    clippy::unwrap_used,
525    clippy::unwrap_in_result,
526    clippy::panic_in_result_fn,
527    clippy::indexing_slicing,
528    clippy::arithmetic_side_effects,
529    reason = "Standard repository test boilerplate"
530)]
531mod tests {
532    use ctb_utilities::anyhow::ensure;
533
534    use super::*;
535
536    fn approx_eq(a: f64, b: f64, tol: f64) -> bool {
537        (a - b).abs() <= tol
538    }
539
540    #[crate::ctb_test]
541    fn basic_math() -> Result<()> {
542        ensure!(abs(-3.5) == 3.5);
543
544        ensure!(divzero(10.0, 0.0) == 0.0);
545        ensure!(divzero(10.0, 2.0) == 5.0);
546
547        ensure!(fix(4.6)? == 4.0);
548        ensure!(fix(-4.6)? == -4.0);
549
550        ensure!(int(4.6)? == 4.0);
551        ensure!(int(-4.6)? == -5.0);
552
553        ensure!(max(3.0, 4.0) == 4.0);
554        ensure!(min(3.0, 4.0) == 3.0);
555
556        ensure!(numsandwich(0.0, 7.0) == 0.0);
557        ensure!(numsandwich(20.0, 7.0) == 27.0);
558
559        ensure!(approx_eq(round(16.0, 12.0)?, 12.0, 1e-12));
560        ensure!(approx_eq(round(20.0, 12.0)?, 24.0, 1e-12));
561
562        ensure!(zeroblank(0.0).is_none());
563        ensure!(zeroblank(1.0) == Some(1.0));
564
565        Ok(())
566    }
567
568    #[crate::ctb_test]
569    fn trig_and_logs_domains() -> Result<()> {
570        ensure!(arcsin(2.0).is_err());
571        ensure!(arccos(-2.0).is_err());
572        ensure!(arctanh(1.0).is_err());
573        ensure!(arccosh(0.5).is_err());
574        ensure!(log(0.0).is_err());
575        ensure!(log10(-1.0).is_err());
576        ensure!(sqr(-1.0).is_err());
577
578        Ok(())
579    }
580
581    #[crate::ctb_test]
582    fn trig_and_logs_values() -> Result<()> {
583        let pi = core::f64::consts::PI;
584
585        ensure!(approx_eq(sin(pi / 2.0)?, 1.0, 1e-12));
586        ensure!(approx_eq(cos(0.0)?, 1.0, 1e-12));
587        ensure!(approx_eq(tan(0.0)?, 0.0, 1e-12));
588
589        ensure!(approx_eq(exp(0.0)?, 1.0, 1e-12));
590        ensure!(approx_eq(log(exp(2.0)?)?, 2.0, 1e-12));
591        ensure!(approx_eq(log10(1000.0)?, 3.0, 1e-12));
592
593        Ok(())
594    }
595
596    #[crate::ctb_test]
597    fn factorial() -> Result<()> {
598        ensure!(fact(0.0)? == 1.0);
599        ensure!(fact(5.0)? == 120.0);
600        ensure!(fact(171.0).is_err());
601        ensure!(fact(-1.0).is_err());
602        ensure!(fact(3.5).is_err());
603
604        let n = fact_exact(10)?;
605        ensure!(n == Natural::from(3628800_u32));
606
607        Ok(())
608    }
609
610    #[crate::ctb_test]
611    fn random_is_in_range() -> Result<()> {
612        let mut rng = PanRng::new(123456);
613
614        let r = rng.rnd()?;
615        ensure!((0.0..1.0).contains(&r));
616
617        for _ in 0..100 {
618            let x = rng.randominteger(-3, 3)?;
619            ensure!((-3..=3).contains(&x));
620        }
621
622        Ok(())
623    }
624
625    #[crate::ctb_test]
626    fn financial_examples_magnitude() -> Result<()> {
627        let rate = 0.135 / 12.0;
628        let payment = pmt(rate, 36.0, 20000.0, 0.0, 0.0)?;
629        ensure!(approx_eq(payment.abs(), 678.71, 0.02));
630
631        let f1 = fv(0.09, 10.0, -500.0, 0.0, 1.0)?;
632        ensure!(approx_eq(f1, 8280.15, 0.02));
633
634        let f2 = fv(0.09, 10.0, -500.0, -2000.0, 1.0)?;
635        ensure!(approx_eq(f2, 13014.87, 0.02));
636
637        let p = pv(0.1, 3.0, 1000.0, 0.0, 0.0)?;
638        ensure!(approx_eq(p.abs(), 2486.0, 1.0));
639
640        Ok(())
641    }
642}