1个不稳定版本
| 0.4.3 | 2023年8月18日 |
|---|
#1789 在 数学
40 每月下载量
用于 2 个crates(通过 astroport-liquidity-helpe…)
270KB
7K SLoC
cw-bigint
这是从rust-num/num-bigint分支出来,移除了浮点运算,因此可以用于智能合约。
lib.rs:
大整数(有符号版本:BigInt,无符号版本:BigUint)。
BigUint表示为BigDigit的向量。一个BigInt是BigUint和Sign的组合。
常见的数值操作被重载,因此我们可以像处理其他数字一样处理它们。
示例
use num_bigint::BigUint;
use num_traits::{Zero, One};
use std::mem::replace;
// Calculate large fibonacci numbers.
fn fib(n: usize) -> BigUint {
let mut f0: BigUint = Zero::zero();
let mut f1: BigUint = One::one();
for _ in 0..n {
let f2 = f0 + &f1;
// This is a low cost way of swapping f0 with f1 and f1 with f2.
f0 = replace(&mut f1, f2);
}
f0
}
// This is a very large number.
println!("fib(1000) = {}", fib(1000));
生成大随机数很容易
use num_bigint::{ToBigInt, RandBigInt};
let mut rng = rand::thread_rng();
let a = rng.gen_bigint(1000);
let low = -10000.to_bigint().unwrap();
let high = 10000.to_bigint().unwrap();
let b = rng.gen_bigint_range(&low, &high);
// Probably an even larger number.
println!("{}", a * b);
有关启用随机数生成的说明,请参阅“特性”部分。
特性
默认启用了stdcrate特性,在Rust 1.36之前以及稳定化的alloccrate之前是必需的。如果您依赖于不带num-bigint的default-features = false的num-bigint,并且您的编译器不够新,则必须手动启用std特性。
随机生成
num-bigint在启用rand特性时支持生成随机大整数。要启用它,请包含rand:
rand = "0.8"
num-bigint = { version = "0.4", features = ["rand"] }
请注意,您必须使用与num-bigint兼容的rand版本:0.8。
兼容性
num-bigintcrate已针对rustc 1.31及更高版本进行测试。
依赖关系
~140–600KB
~11K SLoC