Skip to content
Related Articles

Related Articles

Python – math.ulp(x) function

Improve Article
Save Article
  • Last Updated : 23 Aug, 2021
Improve Article
Save Article

ULP stands for “Unit in the Last Place”. math.ulp() is introduced in python 3.9.0 version, it returns the value of the least significant bit of the float x. In numerical analysis and computer science, unit of least precision (ULP) or unit in the last place is the spacing between floating-point numbers.

Note:

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

Syntax: math.ulp(x)

Parameter:

x: float whose ulp is returned

Return:

Return the value of the least significant bit of the float x.

Example: To show the working of math.ulp(x) method.

Python3




# python program to explain
# math.ulp(x) for different values of x
import math
import sys
 
# when x is NaN
x = float('nan')
print(math.ulp(x))
 
# when x is positive infinity
x = float('inf')
print(math.ulp(x))
 
# when x is negative infinity
print(math.ulp(-x))
 
# when x = 0
x = 0.0
print(math.ulp(x))
 
# when x is maximum representable float
x = sys.float_info.max
print(math.ulp(x))
 
# x is a positive finite number
x = 5
print(math.ulp(x))
 
# when x is a negative number
x = -5
print(math.ulp(x))


Output:

nan
inf
inf
5e-324
1.99584030953472e+292
8.881784197001252e-16
8.881784197001252e-16
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!