使用浮点数的序列之和 [英] sum of series using float

查看:50
本文介绍了使用浮点数的序列之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我计算了该系列的前20个元素-

I calculated the first 20 elements of the series -

有2种方式,第一种-向前,第二种-向后.为此我做了-

in 2 ways , 1st - forward , 2nd - backward. For this I did -

#include <iostream>
#include <math.h>
using namespace std;

float sumSeriesForward(int elementCount) {
    float sum = 0;
    for (int i = 0; i < elementCount; ++i) {
        sum += (float) 1 / (pow(3, i));
    }
    return sum;
}

float sumSeriesBack(int elementCount) {
    float sum = 0;
    for (int i = (elementCount - 1); i >= 0; --i) {
        sum += (float) 1 / (pow(3, i));
    }
    return sum;
}

int main() {
    cout.precision(30);
    cout << "sum 20 first elements - forward: " << sumSeriesForward(20) << endl;
    cout << "sum 20 first elements - back: " << sumSeriesBack(20) << endl;
}

我得到了-

sum 20 first elements - forward: 1.5000001192092896
sum 20 first elements - back: 1.5

有人可以解释为什么这两种方式之间有何区别吗?

Can someone please explain why is the difference between the 2 ways ?

推荐答案

通常,浮点数不能精确表示值.当您对值进行操作时,错误会传播.在您的示例中,向后计算时,您会向越来越大的数字添加较小的值,到目前为止,很有可能这些较小的数字的总和会对较大的数字产生影响.另一方面,当您进行正向计算时,您会从大数字开始,而小数字对它的影响会越来越小.也就是说,求和时总希望最小到最大.

In general, floating point numbers cannot represent values exactly. When you operate on the values errors propagate. In your example, when computing backwards you add small values to ever bigger numbers, having a good chance that the sum of the small numbers so far has an effect on the bigger number. On the other hand, when you compute forward you start with the big numbers and the smaller numbers have ever less effect on it. That is, when summing you always want to sum smallest to biggest.

只需考虑将总和保持固定的位数即可.例如,保留4位数字并将这些数字从上到下和从下到上求和:

Just consider keep a sum in just a fixed number of digits. For example, keep 4 digits and sum these numbers top to bottom and bottom to top:

values   top to bottom   bottom to top
10.00      10.00            10.01
0.004      10.00            0.010
0.003      10.00            0.006
0.002      10.00            0.003
0.001      10.00            0.001

浮点数的工作方式相同,使用固定数量的[二进制]数字.

Floating point numbers work just the same way, using a fixed number of [binary] digits.

这篇关于使用浮点数的序列之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆