c++ - C++ 中的减法 double

标签 c++ floating-point subtraction

<分区>

我正在做家庭作业,我需要使用麦克劳林级数来评估 cosh(x) 和 sin(x)。每次程序运行时,用户输入一个 0-10 的数字来指定要评估该系列的项数。然后用户输入 x 的值来评估。一旦用户点击回车,将计算并打印出该系列的 10 个增量。此外,我还必须找到确切的错误。为此,我为 sinh 和 cosh 创建了几个不同的函数来执行特定项的计算。例如:下面的代码评估术语 up to 10!。

void cosFunction10(double power, double value)
{
     double cosh_x = 0;
     double math_cosh = 0;
     double exact_error;
     double x;

     if (value < 0)
         x = -0.1*0;

     for (int i = 0; i < 11; ++i)
     {
         cosh_x = (1.0 + ((x*x)/(2.0*1.0)) + ((x*x*x*x)/(4.0*3.0*2.0*1.0)) + ((x*x*x*x*x*x)/(6.0*5.0*4.0*3.0*2.0*1.0)) + ((x*x*x*x*x*x*x*x)/(8.0*7.0*6.0*5.0*4.0*3.0*2.0*1.0)) + ((x*x*x*x*x*x*x*x*x*x)/(10.0*9.0*8.0*7.0*6.0*5.0*4.0*3.0*2.0*1.0)));
         math_cosh = cosh(x);
         exact_error = (math_cosh - cosh_x);

         cout << setiosflags(ios::scientific) << setprecision(3) << x << "\t";
         cout << setiosflags(ios::scientific) << setprecision(5) << cosh_x << "\t";
         cout << math_cosh << "\t";
         cout << exact_error << endl;
         x = x + (0.1*value);
     }
 }

如果我运行程序并输入这些值:10(第 n 个项)和 -6(x 的值)。

这是我应该得到的: (第二次增量)

 x                Series            Exact (using the cmath functions)    Exact % Error
 -6.000e-001      1.18547e+000      1.18547e+000                        0.00000e+000

对于确切的错误,接下来的 2 个输出将是相同的,直到我到达第 4 个增量

 x                Series            Exact (using the cmath functions)    Exact % Error
 -1.800e+100      3.10747e+000      3.10747e+000                        -7.67243e-005

当我运行我的代码时,我没有得到以上结果: (第二次增量)

 x                Series            Exact (using the cmath functions)    Exact % Error
-6.000e-001      1.18547e+000      1.18547e+000                         4.55325e-012

所以似乎出了点问题,因为我的确切错误与我给出的错误甚至不相近。我知道可能会有轻微的不同值,这是预料之中的,但不会到这个程度。

如有任何建议,我们将不胜感激

谢谢

最佳答案

必须有这样的差异,因为 cosh(x) 是根据下面给出的公式以不同的方式定义的:

enter image description here

请参阅here更多细节。

但是,如果您根据 MacLaurin 级数的计算来计算金额,问题是您没有以正确的方式累加值。下面的实现可能是您实际需要的:

void cosFunction(double x)
{
    double cosh_x = 1;
    double math_cosh;
    double exact_error;
    double factorial = 1;
    double x_pow = 1;

    for (int i = 0; i < 11; ++i) {
            cosh_x = x_pow/factorial;
            x_pow = x*x*x_pow; 
            factorial = factorial* (2 * i + 1) * (2 * i + 2);
    }

    math_cosh = cosh(x);
    exact_error = (math_cosh - cosh_x);
    cout << setiosflags(ios::scientific) << setprecision(5) << exact_error << endl;

}

关于c++ - C++ 中的减法 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12869679/

相关文章:

c++ - 定义双感叹号?

c++ - std::cout 同时在下方输出更多文本

从 double 转换为 float

javascript - 为什么 jQuery 减法输出 NaN?

python - 如何解决AttributeError : 'module' object has no attribute 'createBackgroundSubtractorMOG' in opencv?

c++ - 线程完成后 boost 线程工作对象的重用

c++ - 混淆右值引用和 const 左值引用作为参数

c - 使用幂函数时的 float 与整数

c++ - 当通过 C/C++ 中的 double 传输时,是否保证保留 float ?

java - 编写一个接受列表的减法循环