#rational-numbers #integer-arithmetic #integer #rational #numbers #arbitrary-precision

reckoner

一个支持整数和有理数的任意精度算术的高级别库

4个版本

0.2.0 2022年10月25日
0.1.2 2021年4月18日
0.1.1 2021年4月18日
0.1.0 2020年1月14日

#314 in 数学

MIT 协议

630KB
15K SLoC

Rust 10K SLoC // 0.2% comments C 4.5K SLoC // 0.2% comments Python 151 SLoC // 0.4% comments Shell 32 SLoC // 0.1% comments

Reckoner

一个高层次的任意精度整数和有理数算术库,封装了 imath

示例

以下示例使用 牛顿/欧拉收敛变换 计算π的近似值。

use reckoner::{Integer, Rational};

fn factorial(v: &Integer) -> Integer {
    let mut accum = 1.into();
    let mut f = v.clone();

    while f > 0 {
        accum *= &f;
        f -= 1;
    }

    accum
}

// Product of all odd integer up to the given value.
fn odd_factorial(v: &Integer) -> Integer {
    let mut accum = 1.into();
    let mut f = if v % 2 == 0 { v - 1 } else { v.clone() };

    while f > 0 {
        accum *= &f;
        f -= 2;
    }

    accum
}

// ```
// \frac{\pi}{2}
//     = \sum_{k=0}^\infty\frac{k!}{(2k+1)!!}
//     = \sum_{k=0}^{\infty} \cfrac {2^k k!^2}{(2k + 1)!}
//     = 1+\frac{1}{3}\left(1+\frac{2}{5}\left(1+\frac{3}{7}\left(1+\cdots\right)\right)\right)
// ```
fn compute_pi_approx(iterations: u32) -> Rational {
    2 * (0..iterations)
        .map(Integer::from)
        .map(|n| {
            let numerator = factorial(&n);
            let denominator = odd_factorial(&(2 * n + 1));

            (numerator, denominator).into()
        })
        .sum::<Rational>()
}

更多信息请参阅 examples/

Crate

两个Crate的MSRV都是 1.64.0

reckoner

crates.io docs.rs

一个支持整数和有理数的任意精度算术的高级别库。

creachadair-imath-sys

crates.io docs.rs

imath 的FFI绑定。

文档

reckoner 的主文档

creachadair-imath-sys 的主文档

依赖

~0–2.5MB
~41K SLoC