tags:

views:

65

answers:

2

In C++, What are the random digits that are displayed after giving setprecision() for a floating point number?

Note: After setting the fixed flag.

example:

float f1=3.14;
cout < < fixed<<setprecision(10)<<f1<<endl;

we get random numbers for the remaining 7 digits? But it is not the same case in double.

+1  A: 

They're not really "random" -- they're the (best available) decimal representation of that binary fraction (will be exact only for fractions whose denominator is a power of two, e.g., 3.125 would display exactly).

Of course that changes depending on the number of bits available to represent the binary fraction that best approaches the decimal one you originally entered as a literal, i.e., single vs double precision floats.

Not really a C++ specific issue (applies to all languages using binary floats, typically to exploit the machine's underlying HW, i.e., most languages). For a very bare-bone tutorial, I recommend reading this.

Alex Martelli
+4  A: 

Two things to be aware of:

  1. floats are stored in binary.
  2. float has a maximum of 24 significant bits. This is equivalent to 7.22 significant digits.

So, to your computer, there's no such number as 3.14. The closest you can get using float is 3.1400001049041748046875.

double has 53 significant bits (~15.95 significant digits), so you get a more accurate approximation, 3.140000000000000124344978758017532527446746826171875. The "noise" digits don't show up with setprecision(10), but would with setprecision(17) or higher.

dan04