`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

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

Alex

June 18, 2009 at 11:48 AMHey, 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.

mysteriousbooger

September 29, 2009 at 12:13 PMa/(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)

Martin Bonner

June 14, 2010 at 9:16 AMIt 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

iOS Apps Development

May 2, 2012 at 11:43 AMfunny my own minfloat kept returning 0.5 and -0.5 respectively. any help as to why? i'm a python programmer.

Daniel Ariba

May 19, 2013 at 5:54 PMGreat information here Seun! Thanks a lot for this wonderful detail, i think our web hosting servers should also upgrade too.

moses emoekpere

April 12, 2014 at 5:28 AM