c++ - 计算负实数值的 Gamma 函数(C++、Boost)

标签 c++ boost c++17 factorial gamma-function

以下无限严重需要计算非整数、负、实数的阶乘:
Infinite serious:
(这是一种计算椭圆周长的方法,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
我的问题:
  • 是否有替代 boost 可以计算其负域的 Gamma 函数?
  • 我在上面链接的 boost 文档中找不到阶乘和 tgamma 函数的实现域。事实上,我可能只是错误地使用了它们。确定域/正确用法确实是什么的方法是什么?

  • 谢谢。

    最佳答案

    自 C++11 [1] 起,Gamma 函数成为标准库的一部分。
    用法如下:

    #include <cmath>
    
    std::tgamma(-0.5) # -3.5449077
    std::lgamma(-0.5) # 1.2655121
    
    您不妨使用 tgammaltgammaflong doublefloat类型相应。
  • https://en.cppreference.com/w/cpp/numeric/math
  • 关于c++ - 计算负实数值的 Gamma 函数(C++、Boost),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63056272/

    相关文章:

    c++ - 如何统计一个对象的引用次数?

    c++ - 在 boost scope exit 中调用对象函数

    c++ - 如何使 boost::serialization 反序列化更快?

    c++ - 使用空函数调用 hana::is_valid 的用途是什么?

    c++ - 为什么在增加 -fconstexpr-steps 后无法解析常量表达式?

    c++ - 系统范围的 libxml2 不工作,从源代码编译在配置中失败

    c++ - 自动使用派生类

    c++ - Boost.Log 宏扩展和条件三元运算符

    c++ - 我可以将 braced-init-list 用于 std::variant 的 vector 吗?

    c++ - 将 IP 地址从 sockaddr 转换为 in_addr