Smallest And Largest Floating Point Values In Python

In my production code, I have a function that calculates a/(a+b). That function threw a ZeroDivisionError at me this afternoon, so I decided to change the equation to a/(a+b+sys.minfloat), because I felt that was more elegant than writing a conditional function to check if (a + b) == 0.

Turns out there is no 'minfloat' in the sys module, so I decided to write a function to calculate the smallest float myself.
>>> def minfloat(guess):
while(guess * 0.5 != 0):
guess = guess * 0.5
return guess

>>> minfloat(+1.0) # minimum positive value of a float
4.9406564584124654e-324

>>> minfloat(-1.0) # minimum negative value of a float
-4.9406564584124654e-324


But I couldn't stop there. Now I had to write a function to calculate the largest possible floating point value in Python, just for kicks:
>>> def maxfloat(guess = 1.0):
while(guess * 2 != guess):
guess = guess * 2
return guess

>>> maxfloat(+1.0) # maximum positive value of a float
inf

>>> maxfloat(-1.0) # maximum negative value of a float
-inf


This is interesting. Let's find out more about this "inf" value:
>>> inf

Traceback (most recent call last):
File "", line 1, in
inf
NameError: name 'inf' is not defined
>>> float("inf")
inf

>>> inf = maxfloat()

>>> inf + inf
inf

>>> inf - inf
nan

>>> 1 / inf
0.0

>>> 1/(-inf)
-0.0


Finally, check the relationship between minfloat and maxfloat:
>>> 1 / minfloat(1.0)
inf
>>> 1 / minfloat(-1.0)
-inf

6 comments :: Smallest And Largest Floating Point Values In Python

  1. You can actually get the inf float by doing float('inf').

  2. Hey, I saw a post of yours on stackoverflow.com about simply adding RAM to a server to compensate for poor coding of PHP. Is this true? Can you send me an email at whadu@brokencontrollers.com?

    Thanks in advance for a reply.

  3. a/(a+b+minfloat) isn't a complete fix. If a+b==-minfloat, then you still get a divide by zero. For this to be true, you need a and b to be quite small otherwise the smallest amount they can differ by is greater than minfloat (whereas b can always equal -a, whatever the size of a)

  4. It is really nice for me to see you and your great hardwork again.Every piece of your work look excellent.Looking forward to learing more from you!
    Web Apps

  5. funny my own minfloat kept returning 0.5 and -0.5 respectively. any help as to why? i'm a python programmer.

  6. Great information here Seun! Thanks a lot for this wonderful detail, i think our web hosting servers should also upgrade too.

Post a Comment