Python math.nextafter() Function
In floating-point computation, understanding the relationship betweenadjacent floating-point numbersis very important. Floating-point numbers in a computer are discrete, with a minimum gap between two adjacent floating-point numbers.
math.nextafter() is a function introduced in Python 3.9 that returns the value obtained by moving a specified number of floating-point steps from x toward y.
Word meaning: nextafter means "next after".
Basic syntax and parameters
Syntax format
import math
math.nextafter(x, y[, steps])
Parameter Description
- x: the starting floating-point number
- y: the target direction
- steps(optional): the number of steps, defaults to 1
Return Value
Returns the floating-point number obtained by moving steps steps from x toward y
Example
Example 1: getting adjacent floating-point numbers
Example
import
math
next_val
=
math
.
nextafter
(
1.0
,
math
.
inf
)
(
f
"The next floating-point number after 1.0: {next_val}"
)
(
f
"Difference: {next_val - 1.0}"
)
prev_val
=
math
.
nextafter
(
1.0
,
math
.
inf
)
(
f
"The floating-point number before 1.0: {prev_val}"
)
(
f
"Difference: {1.0 - prev_val}"
)
Result:
1.0 的下一个浮点数: 1.0000000000000002
差值: 2.220446049250313e-16
1.0 的前一个浮点数: 0.9999999999999999
差值: 1.1102230246251565e-16
Example 2: the steps parameter
Example
import
math
(
"Move forward 10 steps:"
,
math
.
nextafter
(
1.0
,
math
.
inf
,
10
)
)
(
"Negative step count:"
,
math
.
nextafter
(
1.0
,
math
.
inf
,
5
)
)
Result:
前进 10 步: 1.0000000000000007
负数步数: 0.9999999999999996
Example 3: special values
Example
import
math
(
"Infinity:"
,
math
.
nextafter
(
math
.
inf
,
0
)
)
(
"After 0:"
,
math
.
nextafter
(
0.0
,
1.0
)
)
(
"Negative zero:"
,
math
.
nextafter
(
0.0
,
1.0
)
)
Result:
无穷大: 1.7976931348623157e+308
0 之后: 5e-324
负零: 5e-324
Example 4: computing ULP
Example
import
math
for
x
in
[
1.0
,
2.0
,
100.0
]
:
ulp
=
math
.
nextafter
(
x
,
math
.
inf
)
- x
(
f
"ULP({x}) = {ulp}"
)
Result:
ULP(1.0) = 2.220446049250313e-16
ULP(2.0) = 4.440892098500626e-16
ULP(100.0) = 2.8421709430404007e-14
Notes
- Only available in Python 3.9+
- The steps parameter was also added in Python 3.9
- Useful for understanding floating-point precision limits
Python math Module