0

I would like to see float and double content, but i get a lot of additional unexpected precision digits.

printf("%.55f\n", 1.123456789012345);
cout << setprecision(100) << 1.123456789012345 << endl;

1.1234567890123450251138592648203484714031219482421875000 1.1234567890123450251138592648203484714031219482421875

while i was expecting something like this:

1.12345678901234500...
1.123456789012345

In Octave i also get unexpected output:

>> format long
>> single(1.123456789012345)
ans =  1.12345683574677
Yola
  • 18,496
  • 11
  • 65
  • 106
  • 6
    While not a straight duplicate, [this old question and its answers](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) might help you understand. – Some programmer dude Jan 16 '18 at 14:05
  • @Someprogrammerdude i thought before being stored in memory number got truncated to available precision bits and only saved bits considered afterwards. – Yola Jan 16 '18 at 14:08
  • The `std::setprecision` stream manipulator does not in any way enhance the underlying type precision. What you are seeing is just some random noise. The maximum precision you can set for `double` representation is: `std::setprecision(std::numeric_limits::digits10 + 1)`. – Ron Jan 16 '18 at 14:38
  • @Yola it does but each bit represent a binary fraction: try and extend this sequence to the 24 bit: 1st bit 1/2 (0.5); 2nd bit 1/4 (0.25) 3rd bit 1/8 (0.125); 4th bit 1/16 (0.0625) etc – Richard Critten Jan 16 '18 at 14:53

1 Answers1

3

I would like to see float and double content

You are actually observing the decimal number closest to 1.123456789012345 that can be exactly represented by the floating-point representation. Note that some other decimal numbers like 1 can be represented exactly by the floating-point representation.

Thus, running:

std::cout << std::setprecision(100) << 1.123456789012345 << std::endl;
std::cout << std::setprecision(100) << 1.0 << std::endl;
std::cout << std::setprecision(100) << 1.1 << std::endl;
std::cout << std::setprecision(100) << 1.5 << std::endl;

will print:

1.1234567890123450251138592648203484714031219482421875
1
1.100000000000000088817841970012523233890533447265625
1.5

I higly recommend reading excellent What Every Computer Scientist Should Know About Floating-Point Arithmetic by David Goldberg.

AMA
  • 4,114
  • 18
  • 32
  • The article by David Goldberg you propose to read is very complicated and has nothing to do with this simple issue. Thanks for your answer. – Yola Jan 16 '18 at 14:20
  • 4
    @Yota, While the article might seem subjectively hard to comprehend it describes the basic knowledge everyone working with floating-point numbers should have. – AMA Jan 16 '18 at 14:26
  • 2
    @AMA • Good call on Goldberg's article. Hits the nail on the head for this kind of issue. – Eljay Jan 16 '18 at 14:30