3 个版本 (破坏性)
0.3.0 | 2022 年 12 月 5 日 |
---|---|
0.2.0 | 2022 年 9 月 20 日 |
0.1.0 | 2022 年 9 月 16 日 |
#1645 in 数学
67KB
1.5K SLoC
用于计算骰子离散概率分布的 crate。
为 WASM 构建
对于 bundler(默认)
wasm-pack build --release --no-default-features --features wasm
带有更好的错误消息
wasm-pack build --release --no-default-features --features wasm --features console_error_panic_hook
需要在 Cargo.toml 中包含此内容
[profile.release]
debug = true
如果您不使用 Web bundler
wasm-pack build --target web --release --features wasm --no-default-features
创建并使用 Dice
要创建 Dice
,可以从 DiceBuilder
构建它或直接从字符串构建
let dice: Dice = DiceBuilder::from_string("2d6").unwrap().build()
let dice: Dice = Dice::build_from_string("2d6").unwrap()
这些骰子的属性在 build()
函数中计算
min: 2
max: 12
mode: vec![7],
mean: 7,
median: 7,
distribution: vec![(2, 1/36), (3, 1/18), (4, 1/12), (5, 1/9), (5, 1/9), (6, 5/36), (7, 1/6), ...]
cumulative_distribution: vec![(2, 1/36), (3, 1/12), (4, 1/6), ...]
如果 input
字符串无法解析为适合 DiceBuilder
的正确语法树,则可能会返回 DiceBuildingError。
要掷骰子,调用 roll()
函数
let num = dice.roll();
// num will be some i64 between 2 and 12, sampled according to the dices distribution
要多次掷骰子,请调用 roll_many()
函数
let nums = dice.roll_many(10);
// nums could be vec![7,3,9,11,7,8,5,6,3,6]
语法示例
以下字符串可以传递给 DiceBuilder::from_string(input)
函数
3 个六面骰子
"3d6", "3w6" or "3xw6"
一个六面骰子乘以 3
"3*d6" or "d6*3"
掷一个或两个六面骰子并将它们相加
"d2xd6"
两个六面骰子的最大值减去最小值
"max(d6,d6)-min(d6,d6)""
掷骰子,但任何小于 2 的值变为 2,大于 5 的值变为 5
"min(max(2,d6),5)"
乘以 3 个二十面骰子
"d20*d20*d20"
背景信息
此 crate
使用 BigFraction
数据类型从 fraction
crate 来表示概率。这相当好,因为它允许使用无限精度来精确表示概率。缺点是它比使用浮点数效率低。
当使用"d100*d100"
时,对我来说大约需要100毫秒,而类似“d10xd100”的计算概率分布则耗时9.000毫秒。还有优化的空间。
依赖项
~4–8MB
~149K SLoC