Search code examples
pythonnumpyepsilon

Calculating closest numbers numpy


I'm trying to calculate the closest numbers to 0 but couldn't get what I want so far.

I have a quite simple code;

y = 0.0
x = 0.1
while (y + x > y):
    x = x/2.0
x*2

But I keep getting 0.0 as output. How can I fix this


Solution

  • I guess you want to Keep dividing until x becomes so small it becomes to zero (in floating point format). In the last iteration of your loop x becomes finally zero and the loop condition turnes out to be false: 0.0(y) + 0.0(x) > 0.0(y). At the last line you try to retrieve the x-value by multiplying by two. But x is already zero, so the result is also zero. Mathematically is makes total sense, but the floating point value is already zero at that point.

    In order to keep the latest non-zero value use a second variable:

    y = 0.0
    x = 0.1
    smallest_x = x
    
    while (y + x > y):
        smallest_x = x
        x = x/2.0
    x*2
    

    Or alternatively you check beforehand if x becomes zero after divinding once more:

    y = 0.0
    x = 0.1
    while (y + x/2.0 > y):   //checking if the next division makes x to zero
        x = x/2.0
    x*2
    

    Or take a different approach to get the smallest x:

    x = 1.0
    while (x/2.0 != 0):
        x = x/2.0