我想将二项式系数计算为整数,最多约numberLeaves=100, K=10
. 我相信这应该可以存储在大约 128 位整数中。
因此,我想boost::multiprecision::cpp_int
用来存储结果,并boost::math::binomial_coefficient<boost::multiprecision::cpp_int>
用来计算它:
// Invalid because the template argument must be a floating-point type!
boost::multiprecision::cpp_int number_branch_combinations =
boost::math::binomial_coefficient<boost::multiprecision::cpp_int>(numberLeaves, K);
不幸的是,即使二项式系数是整数,上面的代码也是无效的,因为boost::math::binomial_coefficient
要求返回值必须是浮点类型,声称:
...模板参数必须是实值类型,例如 float 或 double 而不是整数类型 - 这太容易溢出了!
如前所述,在我的情况下,我希望二项式系数计算的结果适合大约 128 位 - 我希望它是一个整数。
因此,我考虑将boost::multiprecision::cpp_dec_float
其作为模板参数传递给boost::math::binomial_coefficient
,然后将浮点返回值(通过舍入)转换为最接近的整数。
可悲的是,我找不到从 a 转换为 aboost::multiprecision::cpp_dec_float
的方法boost::multiprecision::cpp_int
。似乎库严格禁止执行有损转换boost::multiprecision
:
cpp_int cppi(2);
cpp_dec_float_50 df(cppi); // OK, int to float
df = static_cast<cpp_dec_float_50>(cppr); // OK, explicit rational to float conversion
// However narrowing and/or implicit conversions always fail:
cppi = df; // Compiler error, conversion not allowed
现在我正在编写自己的函数来计算二项式系数,并将值作为整数返回。
我发现很难相信实际上没有任何方法可以boost::math::binomial_coefficient
用来计算二项式系数并将其作为boost::multiprecision::cpp_int
.
是否可以boost::math::binomial_coefficient
用来计算二项式系数并将其返回为boost::multiprecision::cpp_int
?