Minimum or Maximum Float Value in Python 2.5

In Python 2.5, there is a built-in function that tells you the maximum allowable int value:

import sys
print sys.maxint

But there is no corresponding function to do this for float values. Part of the reason may be that it can vary from system to system. But actually, I believe they added this in version 2.6. So this is just a workaround for previous versions.

Using the following code, I tested this on both Windows XP and Red Hat Linux (64-bit).

x = 1.0
while x > 0.0 and str(x) != "inf":
  x *= 10.0
  print x

Not that the value for infinity (“inf” in this case) varies between Linux and Windows. This is the value for my Linux system.

Anyway, this comes up with 1e+308. That’s probably not the absolutely precise number. But it’s close to that. The minimum number is the negative value of this.

If you encounter a situation where Python is giving you an error such as “Numerical result out of range,” you can guess that the system is trying to handle float values greater or less than these limits. A quick and dirty solution to getting around this is to find the max/min values for your environment and hard code them. But you can also find external libraries that help if you need it to be absolutely precise.

Please let me know if you have any additional insights on this.

Leave a Reply