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- returnsTruefor 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- returnsTruefor a finite nonzero number whose magnitude belowsys.float_info.min, which is2.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, and5e-324is the smallest positive float the format can represent.signbit- returnsTruewhen 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. | Value | isnormal | issubnormal | signbit |
|---|---|---|---|---|
| 1. | 1.5 | True | False | False |
| 2. | -2.0 | True | False | True |
| 3. | 1e-100 | True | False | False |
| 4. | 1e-310 | False | True | False |
| 5. | 5e-324 | False | True | False |
| 6. | 0.0 | False | False | False |
| 7. | -0.0 | False | False | True |
| 8. | inf | False | False | False |
| 9. | nan | False | False | False |
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