Rounding error in average calculation

I have some problems with rounding errors in C ++. If I need to calculate the average of two floats aand b, then why is it better to do a+0.5*(b-a)what (a+b)/2? I can’t understand why there should be some difference in the two ways of calculating it.

+4
source share
2 answers

Your formula is correct if you are calculating the average of many numbers. In this case, you can do the following:

& mu; n= 1 / n? Sigma; x i

but when adding the 101st number you will need to add x 101 to & mu; 100where & mu; 100 can be quite large compared to x 101, . , :

& mu; 101= & mu; 100 + 1/n (x 101 - & mu; 100))

, x i , x i.

,

, IEEE. ++ float:

[1,2] 2 -23 1 + n * 2 -23 n {0,..., 2 23}.

[2 j 2 j + 1] [1,2], 2 j.

To, , , :

#include <iostream>
#include <iomanip>
int main() {
    float d = pow(2,-23);
    std::cout << d << std::endl;
    std::cout << std::setprecision(8) << d + 1 << std::endl;
    std::cout << std::setprecision(8) << d + 2 << std::endl; // the precision has been lost
    system("pause");
}

1.19209e-07
1.0000001
2

0

[ : IEEE 754 . , , float 32- IEEE 754, - , FLT_EVAL_METHOD 0.]

a + 0.5 * (b-a): a b , a + b 0.5 * (a + b) , . , a + 0.5 * (b - a) .

:

  • a + 0.5 * (b - a) ; 0.5 * (a + b) .
  • , a + b , 0.5 * (a + b) : , . ( , : a + b , , 0.5 , a + b , 0.5 . , .) a + 0.5 * (b - a) , . , a = -1.0 b = 1.0 + 2^-23. a + 0.5 * (b - a) 0.0. 2^-24.
  • a + 0.5 * (b - a) , a b , . 0.5 * (a + b) .
  • a + 0.5 * (b - a) ( ) , 0.5 * (a + b); , , .

, , a + 0.5 * (b - a) 0.5 * (a + b).

+3

Source: https://habr.com/ru/post/1693502/


All Articles