大浮点和的精度

cod*_*ght 6 c floating-point precision numerical-methods

我试图总结一个正向递减浮点的排序数组.我已经看到,总结它们的最佳方法是开始将数字从最低到最高加起来.我写这个代码的例子是,但是,从最高数字开始的总和更精确.为什么?(当然,总和1/k ^ 2应为f = 1.644934066848226).

#include <stdio.h>
#include <math.h>

int main() {

    double sum = 0;
    int n;
    int e = 0;
    double r = 0;
    double f = 1.644934066848226;
    double x, y, c, b;
    double sum2 = 0;

    printf("introduce n\n");
    scanf("%d", &n);

    double terms[n];

    y = 1;

    while (e < n) {
        x = 1 / ((y) * (y));
        terms[e] = x;
        sum = sum + x;
        y++;
        e++;
    }

    y = y - 1;
    e = e - 1;

    while (e != -1) {
        b = 1 / ((y) * (y));
        sum2 = sum2 + b;
        e--;
        y--;
    }
    printf("sum from biggest to smallest is %.16f\n", sum);
    printf("and its error %.16f\n", f - sum);
    printf("sum from smallest to biggest is %.16f\n", sum2);
    printf("and its error %.16f\n", f - sum2);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

squ*_*age 5

您的代码double terms[n];在堆栈上创建了一个数组,这对程序崩溃之前可以执行的迭代次数设置了一个硬性限制.

但是你甚至都没有从这个数组中获取任何东西,所以没有理由把它放在那里.我改变了你的代码以摆脱terms[]:

#include <stdio.h>

int main() {

    double pi2over6 = 1.644934066848226;
    double sum = 0.0, sum2 = 0.0;
    double y;
    int i, n;

    printf("Enter number of iterations:\n");
    scanf("%d", &n);

    y = 1.0;

    for (i = 0; i < n; i++) {
        sum += 1.0 / (y * y);
        y += 1.0;
    }

    for (i = 0; i < n; i++) {
        y -= 1.0;
        sum2 += 1.0 / (y * y);
    }
    printf("sum from biggest to smallest is %.16f\n", sum);
    printf("and its error %.16f\n", pi2over6 - sum);
    printf("sum from smallest to biggest is %.16f\n", sum2);
    printf("and its error %.16f\n", pi2over6 - sum2);
    return 0;

}
Run Code Online (Sandbox Code Playgroud)

如果以十亿次迭代运行,则最小的第一种方法要准确得多:

Enter number of iterations:
1000000000
sum from biggest to smallest is 1.6449340578345750
and its error 0.0000000090136509
sum from smallest to biggest is 1.6449340658482263
and its error 0.0000000009999996
Run Code Online (Sandbox Code Playgroud)