-1

I have a sample program:

#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
  float a = 33.30;

  double b = 33.30;

  char a1[1024];
  char b1[1024];

  sprintf(a1, "%0.6f", a);
  sprintf(b1, "%0.6lf", b);

  cout << a1 << endl;
  cout << b1 << endl;

  return 0;
}

The output I am getting is:

33.299999
33.300000

I am getting correct result for double and incorrect for float. I am unable to understand this behavior. Any help would be highly appreciated.

Bhawan
  • 2,441
  • 3
  • 22
  • 47
  • https://stackoverflow.com/questions/4264127/correct-format-specifier-for-double-in-printf there is not correct format for float, hence there is conversion from float to double and you get this kind of value – Arkady Godlin Apr 11 '18 at 05:40
  • `double` has more precision than `float` – Sid S Apr 11 '18 at 05:45
  • 1
    `float` has a 23 bit mantissa, equivalent to 6.92 decimal digits of precision; there you are printing 8, it's clear that you'll see the rounding error implicit in the decimal conversion. `double` instead has a 52 bit mantissa - the equivalent of 15.65 decimal digits -, so an 8 significant digits rounding holds plenty well. – Matteo Italia Apr 11 '18 at 05:49

2 Answers2

2

33.3 has no exact bounded binary representation, so converting it to float or double incurs in rounding.

float has a 23 bit mantissa, equivalent to 6.92 decimal digits of precision; there you are asking to print 8 digits, which are more than the available precision, and thus will show the effect or the rounding.

double instead has a 52 bit mantissa, which is equivalent to 15.65 decimal digits; the 8 significant digits print holds well, as you are still printing good digits, unaffected by the rounding.


To make an easier to digest example in our beloved base 10: imagine you had a decimal data type with 15 digits of precision, and you want to store 1/3 in it. The best you can do is to store 0.333333333333333; them you copy it into a data type with 6 digits of precision: it becomes 0.333333.

Now, if you print the first value with 8 decimal digits you get 0.33333333, while for the second one you have 0.33333300 - as you already lost the other digits in the conversion.

That is what is happening here, but with binary floating point instead of decimal.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
0

Here is a good answer to the difference of float vs. double.

What is the difference between float and double?

By default, any magic number (as 33.30 in your program) is processed as double. when you do float a = 33.30;, an error occurred.

gzh
  • 3,507
  • 2
  • 19
  • 23