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

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

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

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

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

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

>>> inf = maxfloat()

>>> inf + inf

>>> inf - inf

>>> 1 / inf

>>> 1/(-inf)

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

7 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 about simply adding RAM to a server to compensate for poor coding of PHP. Is this true? Can you send me an email at

    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.

  7. Nice 1 Seun. In actual sense, minfloat(1.0) resembles 1/minfloat(1.0) in that e-324 is 1/e324 only that the former is infinitesimal and definite while the latter is just inf. Still wondering if √324 = 18 has anything to do with anything being a complete square. *feelingstupid* Lol

Post a Comment