Python math.nextafter() Function

Python math 模块Python math Module


In floating-point calculations, understandingadjacent floating-point numbersThe relationship between them is very important. Floating-point numbers in computers are discrete, and there is a minimum interval between two adjacent floating-point numbers.

math.nextafter()is a function introduced in Python 3.9, used to return the value after advancing a specified number of floating-point steps from x toward y.

Word Meaning: nextafterIt means "after the next".


Basic Syntax and Parameters

Syntax Format

import math

math.nextafter(x, y[, steps])

Parameter Description

  • x: starting floating-point number
  • y: target direction
  • steps(optional): number of steps, default is 1

Return Value

Return the floating-point number after advancing steps steps from x in the direction of y


Examples

Example 1: Get adjacent floating-point numbers

Example

import math

next_val = math.nextafter(1.0, math.inf)
print(f"The next floating-point number after 1.0: {next_val}")
print(f"Difference: {next_val - 1.0}")

prev_val = math.nextafter(1.0, -math.inf)
print(f"\n"The previous floating-point number before 1.0: {prev_val}")
print(f"Difference: {1.0 - prev_val}")

Output:

1.0 的下一个浮点数: 1.0000000000000002
差值: 2.220446049250313e-16
1.0 的前一个浮点数: 0.9999999999999999
差值: 1.1102230246251565e-16

Example 2: steps parameter

Example

import math

print("Forward 10 steps:", math.nextafter(1.0, math.inf, 10))
print("Negative step count:", math.nextafter(1.0, -math.inf, -5))

Output:

前进 10 步: 1.0000000000000007
负数步数: 0.9999999999999996

Example 3: Special Values

Example

import math

print("Infinity:", math.nextafter(math.inf, 0))
print("After 0:", math.nextafter(0.0, 1.0))
print("Negative zero:", math.nextafter(-0.0, 1.0))

Output:

无穷大: 1.7976931348623157e+308
0 之后: 5e-324
负零: 5e-324

Example 4: Calculate ULP

Example

import math

for x in [1.0, 2.0, 100.0]:
    ulp = math.nextafter(x, math.inf) - x
    print(f"ULP({x}) = {ulp}")

Output:

ULP(1.0) = 2.220446049250313e-16
ULP(2.0) = 4.440892098500626e-16
ULP(100.0) = 2.8421709430404007e-14

Notes

  • This function is only available in Python 3.9+
  • The steps parameter is also new in Python 3.9
  • Can be used to understand floating-point precision limitations

Python math 模块Python math Module

Other Extensions