我想将二项式系数计算为最大约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
要求返回值必须是浮点类型claiming that:
...模板参数必须是实值类型,例如float或 double而不是整数类型 - 太容易溢出!
如上所述,在我的情况下,我希望二项式系数计算的结果适合大约128位 - 我希望它是一个整数。
因此,我考虑将boost::multiprecision::cpp_dec_float
作为模板参数传递给boost::math::binomial_coefficient
,然后从浮点返回值(通过舍入)执行转换到最近整数。
可悲的是,我无法将boost::multiprecision::cpp_dec_float
转换为boost::multiprecision::cpp_int
。似乎boost::multiprecision
库执行有损转换是strictly prohibited:
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
返回?
答案 0 :(得分:1)
我发现很难相信实际上没有办法使用
boost::math::binomial_coefficient
计算二项式系数并将其作为a boost::multiprecision::cpp_int
返回。
为什么你认为这么难以相信?
这是一个明确的设计选择,已被记录,当时它非常有意义。
Boost Multiprecision仅在1_53中引入。我认为binomial_coefficient
比这更容易岁月(虽然我没有检查过)。
所以,不应该表达你的厌恶,你应该与boost邮件列表上的开发者交谈以建议这个新功能。 Boost库维护者通常非常渴望与(新)库集成。
正如您将意识到的,您可以暂时包装该功能,进行转换。它是理想的 faaar ,但它比自己为Boost Math提供补丁的工作要少:)
答案 1 :(得分:1)
这是我用来获得总数n选择k:
boost::multiprecision::cpp_int BinomialCoefficient(unsigned int n, unsigned int k) {
if (k == 0) { return 1; }
else { return (n * BinomialCoefficient(n - 1, k - 1)) / k; }
}
这是改编的from this answer,我得说它做得很好。