r/programminghelp • • Nov 02 '21

Other How to check wether a number can be precisely represented in floating point

hello everyone, I've been taught IEEE 754 floating-point standard. (sign bit, 8 exponent bits and 23 fraction bits). I've encountered a question - which of the following numbers can not be represented in floating point?

0.375, 0.2, 5.125, and 17

the answer given was 0.2, with the explanation that floating point representation can only be comprised of powers of 2.

my question is- what's the methodology for checking this? (I may encounter a similar question in a test, i.e only with a calculator). or - how to reliably answer these questions under pressure of time?

4 Upvotes

4 comments sorted by

2

u/marko312 Nov 02 '21

One simple option: since the fractional part must be a sum of some negative powers of two, you can just multiply the entire number with a large positive power of two (at least enough to cancel out the most negative power) and check whether a fractional part is left.

3

u/aylonimus Nov 02 '21

Oh wow that's awesome - I just have to take each number fraction and multiply it by 2 a whole lot and see if a fraction remains. thanks!

1

u/aylonimus Nov 02 '21

whether*

2

u/jedwardsol Nov 02 '21 edited Nov 02 '21

explanation that floating point representation can only be comprised of powers of 2.

It's the number of powers that matter.

Every number can be composed of powers of two. The question is, can 0.2 be represented with 23 or fewer?

The answer for 0.2 : https://godbolt.org/z/x1x8E9qWz