如何绘制任何错误与涉及实数求和的问题的精确解之间的关系

How to plot the relationship between any error and the exact solution of a problem involving summation of real number

我正在学习数值方法class,我们被问到这个问题。 问题如下,

将实数10^-N与其自身相加10^N次。 运行 N = 1 到 12 的程序。 所以我写了下面的 C++ 代码

#include <iostream>
#include <cmath>        // std::pow for power of numbers
#include <iomanip>      // std::setprecision
using namespace std;

int main(){
double i, sum, Nx; // Initialize the variables

for(i = 1; i < 3; i++ ){

Nx = pow(10,i); // Here Nx is the 10^n term.

cout << "Nx: " << Nx << endl;  // Printing Nx before starting the loop

sum = 0;  // Initializing the Total sum to zero

while(Nx){
     sum = sum + pow(10,-i); // Adds every 1/10^i term to itself till 10^i becomes 0.
     Nx--;
     cout << "For i = " << i << " the sum is: " << setprecision(10) << sum << endl; // Printing the summation value
  }
 }
return 0;
}

总和为1。

但是问题的第二部分是以有意义的方式绘制任何错误与精确解之间的关系。

我知道我需要一个对数刻度来绘制它。但是我如何产生错误呢? 任何帮助将不胜感激。

数字 dx=10^-N 本身在其最多为 ULP 的一半的二进制表示中存在舍入误差,或者大约 0.5*mu*dx 其中 mu=2^-52 大约是 2e-16.这些错误的总和最多为0.5*mu,因此不影响结果。

我们来看求和步骤。一开始和很小,因此舍入误差也会相应变小。随着总和的增加,单次加法的误差也会增加。求和到一半,遇到极值的平均,所以看dx=10^-N0.5。加法的舍入误差最多为 ULP 的二分之一,但现在它与结果相关,结果再次约为 0.5,误差为 0.25*mu。以此作为平均误差,整个计算将给出大约 10^N*0.25*mu 左右的误差,即大约 0.5*10^(N-16)。这意味着大约最后 N 位数字是 "dirty"。请注意,舍入误差在大小和方向上具有某种随机分布,因此它们也可以抵消,最终给出比此估计值更小的误差。

在您观察到的情况下,错误将出现在 16 位数字中的最后 3 位。通过四舍五入到 10 位数字,您可以消除打印数字中的错误。您可以做两件事:

  • 增加输出的位数,
  • 也打印 1 的差异。