How to determine a number closest to a given number in floating point.

4.3k Views Asked by At

I am learning to program and came across the interesting byproduct of computer number representation shown by $$0.1+0.2= 0.30000000000000004$$

In trying to understand why this occurs, one has to understand how 0.1 is stored on the computer. I worked out that $$0.1_{(10)}=0.00011001100...\,_{(2)}$$ and subsequently read that the number floating-point numbers closest to $0.1$ are $$0.09999999999999999167332731531132594682276248931884765625$$ $$0.1000000000000000055511151231257827021181583404541015625$$ (source: https://stackoverflow.com/a/27030789).

Curious as to how to actually determine these number(s), I attempted to write a python script to find them and failed miserably. I then turned to google and found this answer to a similar question: https://math.stackexchange.com/a/2119191/22276. I was able to follow the solution completely in my case until the portion computing the numbers 14411518807585587 and 14411518807585588. How do I use these numbers to get the two surrounding numbers.

For reference, my two integers would be determined by:

$$2^{-4}=.0625 \leq 0.1 < .125 = 2^{-3}$$ causing $e=-4$. I then compute the integer part of

$$0.1\cdot 2^{53-(-4)}$$ which is $$144 115 188 075 855 872$$

This is where I am stuck.

1

There are 1 best solutions below

5
On BEST ANSWER

Let $x=0.1, y=0.2, z=0.3$. Let $x', y',z'$ the corresponding values rounded to double precision numbers. You have

    x' = 0.0001100110011001100110011001100110011001100110011001101  (bin)
    x' = 0.1000000000000000055511151231257827021181583404541015625  (dec)
    y' = 0.0011001100110011001100110011001100110011001100110011010  (bin)
    y' = 0.2000000000000000111022302462515654042363166809082031250  (dec)
    z' = 0.0100110011001100110011001100110011001100110011001100110  (bin)
    z' = 0.2999999999999999888977697537484345957636833190917968750  (dec)

Now add $x' + y'$ and get as raw sums

  x'+y' = 0.0100110011001100110011001100110011001100110011001100111 (bin)
  x'+y' = 0.3000000000000000166533453693773481063544750213623046875 (dec)

which would be rounded to

(x'+y')'= 0.010011001100110011001100110011001100110011001100110100 (bin)
(x'+y')'= 0.3000000000000000444089209850062616169452667236328125 (dec)

Not that $x'-x>0$ and $y'-y>0,$ i.e. $x,y$ are rounded-up, while $z'-z <0,$ i.e. $z$ is rounded-down and $x'+ y'$ is rounded-up.