Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setprecision is Confusing

Tags:

c++

I just want to ask about setprecision because I'm a bit confused.

here's the code:

#include <iostream>
#include <iomanip>
using namespace std;

int main()

{
  double rate = x;
  cout << fixed << setprecision(2) << rate;
}

where x = to following:

the left side of equation are the values of x.

1.105 = 1.10 should be 1.11

1.115 = 1.11 should be 1.12

1.125 = 1.12 should be 1.13

1.135 = 1.14 which is correct

1.145 = 1.15 also correct

but if x is:

2.115 = 2.12 which is correct

2.125 = 2.12 should be 2.13

so why in a certain value it's correct but sometimes it's wrong?

please enlighten me. thanks

like image 547
Marc Quebrar Tan Avatar asked Apr 11 '11 15:04

Marc Quebrar Tan


People also ask

What is the purpose of the manipulator Setprecision?

C++ manipulator setprecision function is used to control the number of digits of an output stream display of a floating- point value.

What should be included in Setprecision?

To set the precision in a floating-point, simply provide the number of significant figures (say n) required to the setprecision() function as an argument. The function will format the original value to the same number of significant figures (n in this case).

What does Setprecision mean in C++?

The setprecision is a manipulator function in C++ which is used to sets the decimal precision of floating-point values on output operations. This setprecision is the built-in function defined in <iomanip> header file in C++.


2 Answers

There is no reason to expect that any of the constants in your post can be represented exactly using the floating-point system. As a consequence, the exact halves that you have may no longer be exact halves once you store them in a double variable (regardless of how the iostreams are meant to round such numbers.)

The following code illustrates my point:

#include <iostream>
#include <iomanip>

using namespace std;

int main()

{
  double rate = 1.115;
  cout << fixed << setprecision(20) << rate;
}

Output:

1.11499999999999999112

I would recommend taking a look at the FAQ.

like image 101
NPE Avatar answered Nov 15 '22 23:11

NPE


Some of the numbers you're printing may not be representable as a floating point number and may actually be lower or higher than you think, directly affecting the rounding.

Since you're trying to format a floating point number to fixed point, have you considered actually USING a fixed point number (int/long scaled by say 1000 depending on your needs) that has its own insert operator defined? Then you'll always get accurate display and rounding without needing to rely on setprecision having any particular behavior (I couldn't find the relevant conversion section in the standard in a quick look).

like image 33
Mark B Avatar answered Nov 15 '22 23:11

Mark B