Check Special Floating-Point Values in Python 3.15

Check Special Floating-Point Values in Python 3.15

Not every float is an ordinary number. Alongside regular values, the format also holds zero in both positive and negative forms, infinities, NaN, and very small numbers stored with reduced precision. Comparison operators cannot always tell these apart, because negative zero compares equal to positive zero and every comparison involving NaN is false.

Since Python 3.15, the math module provides three functions that inspect a float directly instead of comparing it.

import math

print(math.isnormal(1.5))  # True
print(math.issubnormal(5e-324))  # True
print(math.signbit(-0.0))  # True
  • isnormal - returns True for a finite nonzero number that is not subnormal. These are ordinary floats, stored with the full 53-bit significand, which covers almost every value a program works with.
  • issubnormal - returns True for a finite nonzero number whose magnitude below sys.float_info.min, which is 2.2250738585072014e-308. Below that threshold the exponent cannot decrease any further, so the significand gives up leading bits to represent the value at all. Such numbers are still usable, but they carry less precision than normal floats, and 5e-324 is the smallest positive float the format can represent.
  • signbit - returns True when the sign bit of a value is set. Unlike a comparison, it reads the sign directly, which makes it the only reliable way to detect the sign of zeroes, infinities and NaN.

The following table shows how the three functions classify a range of values:

No.Valueisnormalissubnormalsignbit
1.1.5TrueFalseFalse
2.-2.0TrueFalseTrue
3.1e-100TrueFalseFalse
4.1e-310FalseTrueFalse
5.5e-324FalseTrueFalse
6.0.0FalseFalseFalse
7.-0.0FalseFalseTrue
8.infFalseFalseFalse
9.nanFalseFalseFalse

Note that 1e-100 is a normal number despite its exponent notation. Scientific notation in the output only reflects how Python displays very small or very large magnitudes, and has nothing to do with whether a value is subnormal.

Leave a Comment

Cancel reply

Your email address will not be published.