c++ - 计算 e^x 的近似值时出错

标签 c++ math logic user-input

我对 C++ 相当陌生,正在编写一个程序来计算 e^x 的近似值。由公式给出:

1 + X + X^2/2! + ... + X^n/n!  (for values of n from 1-100)

程序会完美地计算该值,直到用户为“xValue”输入大于 60(即 61 或更大)的数字。我不确定这是为什么,并且非常感谢一些反馈:

void calculate_sum(CalculateEx& numberSum)
{   
    double factoralSum;


    numberSum.xTotal = numberSum.xValue;
    numberSum.xTotal++;

    for (double counter = 2; counter <= 100; counter++)
        {
            factoralSum = 1;

            for (double factoral = 1; factoral <= counter; factoral++)
                {
                    factoralSum *= factoral;
                }

            numberSum.xNextValue = pow(numberSum.xValue, counter) / factoralSum;
            numberSum.xTotal += numberSum.xNextValue;
        }

    return;
}

最佳答案

不要从头开始计算下一行元素,存储前一个元素,x^(n+1)/(n+1)! == (x^n)/n! * x/(n+1) 。这样您就不必存储 x^n 的值尤其是n!分别(它们太大,无法适合任何合理的类型),而 x^n/n! 的值收敛到 0 为 n上涨。

做这样的事情会做:

double prevValue = 1;
sum = prevValue;
for (size_t power = 1; power < limit; ++power) {
    prevValue *= x / (n + 1);
    sum += prevValue;
}

关于c++ - 计算 e^x 的近似值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25272583/

相关文章:

java - 如何统计数组中元素出现的次数?

string - 通过恰好执行 K 个操作将字符串 S 转换为另一个字符串 T(添加到字符串 S 的末尾/从字符串 S 的末尾删除)

Java - 给定字符串中的所有排列和组合

c++ - vector::_M_range_check 异常

c++ - 用cuda计算一张图片,直接用OpenGL显示

python - 类型错误 : 'int' object is not subscriptable {Python}

algorithm - 实线上间隔的恒定时间隶属度索引?

c++ - 追加函数和 nullptr 不起作用

c++ - Windows 性能调整的资源建议(实时)

python - 使用 python3 计算列表中多个整数的幂的最佳方法是什么?