C ++ floating point precision

Possible Duplicate:
Floating Point Inaccuracy Examples

double a = 0.3;
std::cout.precision(20);
std::cout << a << std::endl;

result: 0.2999999999999999889

double a, b;
a = 0.3;
b = 0;
for (char i = 1; i <= 50; i++) {
  b = b + a;
};
std::cout.precision(20);
std::cout << b << std::endl;

result: 15.000000000000014211

So, a is less than it should be. But if we take “50 times”, the result will be more than it should be.

Why is this? And how to get the right result in this case?

+3
source share
5 answers

To get the correct results, do not set the accuracy more than is available for this number type:

#include <iostream>
#include <limits>
int main()
{
        double a = 0.3;
        std::cout.precision(std::numeric_limits<double>::digits10);
        std::cout << a << std::endl;
        double b = 0;
        for (char i = 1; i <= 50; i++) {
                  b = b + a;
        };
        std::cout.precision(std::numeric_limits<double>::digits10);
        std::cout << b << std::endl;
}

5000 50, - , .

+14

?

, 0,3 - 0,01001100110011001... , 1/3, 0,3333333... . 0.3, 0.29999999999999999988897769753748434595763683319091796875 ( 53 ).

, , , , . :

  • , 4 15.
  • , , .

- .

, , 0,30 0,30 , . .

?

15 , "". , .

+9

, .

, , 0,3, . , , , 0.33333 1⁄3.

, , .

+5

, , "0,3" .

"" - 20 .

+1

All Articles