Python Tutorial Python Advanced Python References Python Libraries

Python math - ulp() Function



The Python math.ulp() function returns the value of the least significant bit of the float x. An ulp is the positive distance between the given float value and the float value next larger in magnitude. The function returns the following:

  • If x is a NaN (not a number), then the result is x.
  • If x is negative, then the result is ulp(-x).
  • If x is a positive infinity, then the result is x.
  • If x is equal to zero, then the result is the smallest positive denormalized representable float (smaller than the minimum positive normalized float, sys.float_info.min).
  • If x is equal to the largest positive representable float, then the result is the value of the least significant bit of x, such that the first float smaller than x is x - ulp(x).
  • Otherwise (x is a positive finite number), then the result is the value of the least significant bit of x, such that the first float bigger than x is x + ulp(x).

Syntax

#New in version 3.9
math.ulp(x)

Parameters

x Required. Specify the float whose ulp is returned.

Return Value

Returns the value of the least significant bit of the float argument.

Example:

The example below shows the usage of ulp() function.

import math
import sys

#when argument is 0.0
print(math.ulp(0.0))

#when argument is positive finite
print(math.ulp(10.0))

#when argument is negative finite
print(math.ulp(-10.0))

#when argument is maximum representable float 
x = sys.float_info.max
print(math.ulp(x),"\n") 

#when argument is positive infinite
print(math.ulp(float('inf')))

#when argument is negative infinite
print(math.ulp(-float('inf')))

#when argument is NaN
print(math.ulp(float('nan')))

The output of the above code will be:

5e-324
1.7763568394002505e-15
1.7763568394002505e-15
1.99584030953472e+292

inf
inf
nan

❮ Python Math Module