How to reproduce C ++ double rounding problem

Floating-point accuracy is limited in C++and for novice programmers, who often cause problems when rounding values.

When teaching students, it is often useful to demonstrate the problem of rounding the number of floating point points. What possible methods do you know to demonstrate such a rounding problem on all compilers C++?

+3
source share
5 answers

First, it should be noted that in the floating point IEEE754 values 1.5, 0.5and 2.0all are accurately represented. So, in this particular example it 1.5never will be 1.499999999999.

, , , , . , 1.1.

:

#include <iostream>
#include <iomanip>

int main() {
   std::cout << std::setprecision(30);
   double d1(1.1);
   std::cout << d1 << "\n";
   double d2(11);
   double eps = d2/10 - d1;
   std::cout << d2 << "\n";
   std::cout << eps << "\n";
   bool equal = (d1 == d2);
   std::cout << equal << "\n";
}

, , , d1 d2 1.1.

, 1/2 , 1/10 .

: , - . 1/7 . . , 1/7 . , 1/10 , , .

, (32 ), (64 ). , , ( ) .

, , .

+4

:

#include <iostream>
using namespace std;

int main() {
  for (double d = 0.0; d != 1.0; d += 0.1)
    cout << d << "\n";
}

, d 1.

+5

I like the following example:

double sum = 0;
for (int i = 0; i < 10; i++, sum += 0.1);
cout << "sum = " << sum << endl;
cout << "(sum == 1.) is " << boolalpha << (sum == 1.)  << endl;

Result:

sum = 1
(sum == 1.) is false

The cause of the conflict is floating point calculations.

+2
source
printf("%.20f\n",0.1f);

or

cout << fixed << setprecision(20) << 0.1f << endl;

:)

+1
source

Try this example:

#include <cstdio>
int main() {
    printf("%.20lf rounded to two decimal places is %.2lf\n", 0.075, 0.075);
    return 0;
}

which prints

0.07499999999999999722 rounded to two decimal places is 0.07

note that 0.075, rounded to two decimal places, should be 0.08, not 0.07, as we see in the output. This example demonstrates the double rounding problem.

+1
source

All Articles