-4

double 5.2 number when i find the binary value of this recurring binary i get as 01000000 00010100 11001100 11001100 11001100 11001100 11001100 11001100 like this when i print the binary value programmatically and refering the websites it is something like this 01000000 00010100 11001100 11001100 11001100 11001100 11001100 11001101 how to calculate the binary bits of a double.

According to my answer it should print as -52 -52 -52 -52 -52 -52 20 64 but the real answer is -51 -52 -52 -52 -52 -52 20 64 how does that one bit change?

1 Answers1

1

If you express a decimal fractional number like "###.2" in a binary fractional number it will be a repeating binary fractional number.

It is infinitely repeating because 0.2 can't be expressed as an finite (limited) sum of binary digits right of the "decimal" point. The first bit stands for 2^(-1)=0.5, the second bit stands for 2^(-2)=0.25 and so on. Just try it for yourself.

If you look at the bit pattern of 5.25, it will be not repeating.

Please read these articles: https://en.wikipedia.org/wiki/Fraction_(mathematics) and https://en.wikipedia.org/wiki/Repeating_decimal.

As a double has a limited size the infinitely repeating number has to be cut at some point. And so in the first case the representation was rounded down, and in the second case it was rounded up.

For some more information see When should I use double instead of decimal? even it's for C#.

the busybee
  • 10,755
  • 3
  • 13
  • 30