5个不稳定版本

使用旧的Rust 2015

0.3.1 2021年10月19日
0.3.0 2021年10月17日
0.2.1 2021年7月17日
0.2.0 2021年7月15日
0.1.0 2021年7月14日

753数据结构

32 每月下载量

MIT 许可证

97KB
2K SLoC

fdec

为生成恰好适合您域的固定大小的定点数值类型的宏集合。这些类型已经完全配备了进行数学计算的功能,并且易于使用。

通过简单的宏调用,您将获得一个类型,

  • 在类型参数定义的范围内没有表示错误,
  • 支持算术运算: +-*/%<<>>
  • 包含数学函数: abs()powi()sqrt()
  • 具有特殊的NaN和±Infinity值,并且在出现问题时不会崩溃,
  • 提供基本的数学常数,
  • 无缝与Rust的原始类型交互,
  • 将值转换为/从字节数组转换,
  • 在栈上创建值并执行数学运算,避免堆分配。

何时使用

如果您需要Rust没有提供的原始类型(如 i256i1408),或者您的业务领域不能容忍在计算过程中可能累积的表示错误(如金融中的货币处理),或者您需要存储大量的小数,并且希望它具有内存效率,或者您只是想看看它是如何工作的,那么您可能应该尝试使用fdec。

  • 您应该尝试使用fdec,
  • 您的业务领域不能容忍在计算过程中可能累积的表示错误(如金融中的货币处理),
  • 其他提供小数的库在执行数学运算时不够快,
  • 您需要存储大量的小数,并且希望它具有内存效率,
  • 您只是想看看它是如何工作的。

如何使用

fdec 依赖项添加到您的 Cargo.toml

[dependencies]
fdec = "0.3.1"

使用 macro_use 属性在您的crate根目录导入它

#[macro_use]
extern crate fdec;

通过调用 fdec* 宏将自定义数字类型添加到您的项目中

fdec64! {               // Use 64-bit units
    module bigdec,      // Put all the generated code into the `bigdec` module
    name BigDec,        // The name for the generated type
    length 5,           // 5 * 64-bit units = 320 bits to store numbers
    scale 50            // Use 50 decimal places
}

示例

这里我们定义了一个表示160位数字,具有30个十进制位的 Decimal 结构。

#[macro_use]
extern crate fdec;

fdec32! {            // Use 32-bit units
    module dec,      // Put all the generated code into the `dec` module
    name Decimal,    // Name the main struct `Decimal`
    length 5,        // 5 * 32-bit units = 160 bits to store numbers
    scale 30         // Use 30 decimal places
}

use dec::*;          // Bring the generated stuff to the scope

fn main() {
    // Use it
    let a = Decimal::one();
    let b = Decimal::from(14);
    let c = dec!(9);
    let result = a + 30 * (b / c).powi(3);
    println!("{} + 30 * ({} / {})^3 = {}", a, b, c, result);
    // 1 + 30 * (14 / 9)^3 = 113.92181069958847736625514403278
}

更多示例请查看crate的源代码

  • 多种创建值的方式:[creation.rs](https://github.com/alygin/fdec/tree/master/examples/creation.rs)
  • 计算斐波那契数:[fibonacci.rs](https://github.com/alygin/fdec/tree/master/examples/fibonacci.rs)
  • 使用高精度计算平方根:[sqrt.rs](https://github.com/alygin/fdec/tree/master/examples/sqrt.rs)

依赖项