以下无限严重需要计算非整数、负、实数的阶乘:
(这是一种计算椭圆周长的方法,a 和 b 是长半轴和半短轴,h 定义为:
h = (a-b)^2/(a+b)^2)
阶乘函数可以通过 Gamma 函数扩展到负值,该函数是为所有非负整数的实数定义的。
在编写严肃的代码时,我尝试了 boost::math::factorial 和 boost::math::tgamma ,它们只给出低至 -1(不包括)-1.5 的结果,例如给出错误。
#include <iostream>
#include <boost/math/special_functions/factorials.hpp>
int main()
{
double x;
double f;
double tg;
x = -0.5;
f = boost::math::factorial<double>(x);
tg = boost::math::tgamma<double>(x);
cout << "factorial of " << x << " = " << f << endl;
cout << "tgamma of " << x << " = " << tg << endl << endl;
x = -1.5;
f = boost::math::factorial<double>(x);
tg = boost::math::tgamma<double>(x);
cout << "factorial of " << x << " = " << f << endl;
cout << "tgamma of " << x << " = " << tg << endl << endl;
return 0;
}
输出:factorial of -0.5 = 1
tgamma of -0.5 = -3.54491
terminate called after throwing an instance of 'boost::exception_detail::clone_implboost::exception_detail::error_info_injector<std::domain_error >' what(): Error in function boost::math::tgamma(long double): Evaluation of tgamma at a negative integer 0. Aborted (core dumped)
boost 阶乘:
boost factorial
boost tgamma:
boost tgamma
我的问题:
谢谢。
最佳答案
自 C++11 [1] 起,Gamma 函数成为标准库的一部分。
用法如下:
#include <cmath>
std::tgamma(-0.5) # -3.5449077
std::lgamma(-0.5) # 1.2655121
您不妨使用 tgammal
和 tgammaf
为 long double
和 float
类型相应。关于c++ - 计算负实数值的 Gamma 函数(C++、Boost),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63056272/