简体   繁体   English

C ++中的高斯积分不起作用。 为什么?

[英]Gaussian integral in C++ is not working. Why?

Here is my code: 这是我的代码:

const double kEps(0.00000001);
    double gaussianIntegral(double x)
    {
        double res(x), numerator(x);
        for(unsigned int i(1), k(3); (abs(numerator/k) > kEps) || (res < 0); ++i, k+=2)
        {
            numerator*=(-x*x/i);
            res+=numerator/k;
        }
        return res;
    }

Here is what I am trying to compute: 这是我要计算的内容:

在此处输入图片说明

When I try to pass 30 as an argument my computations go forever. 当我尝试将30作为参数传递时,我的计算将永远失败。 What is wrong? 怎么了? I am very stuck, it seems for me like there is no error and everything should work just fine, but still it is not so. 我非常困惑,对我来说似乎没有错误,一切都应该正常工作,但事实并非如此。

Although formally Taylor series converges, in practice you will run into machine precision limits even for the argument as small as 0.1 (and that is using kEps=0) 尽管正式的泰勒级数收敛,但实际上,即使参数小至0.1(使用kEps = 0),您也会遇到机器精度极限。

It's better to use (scaled appropriately) std::erf (C++11), or if it's a homework, look up an algorithm for computing erf function, eg here: https://math.stackexchange.com/questions/97/how-to-accurately-calculate-the-error-function-erfx-with-a-computer 最好使用(适当缩放) std :: erf (C ++ 11),或者如果是家庭作业,请查找用于计算erf函数的算法,例如: https : //math.stackexchange.com/questions/97 /如何准确计算计算机的错误功能erfx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM