Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python math.nextafter() Function

Python math.nextafter() Function

Python math Module Python math Module


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

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

)

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

"The floating-point number before 1.0: {prev_val}"

)

print

(

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

print

(

"Move forward 10 steps:"

,

math

.

nextafter

(

1.0

,

math

.

inf

,

10

)

)

print

(

"Negative step count:"

,

math

.

nextafter

(

1.0

,

math

.

inf

,

5

)

)

Result:

前进 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

)

)

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

)

   

print

(

f

"ULP({x}) = {ulp}"

)

Result:

ULP(1.0) = 2.220446049250313e-16

ULP(2.0) = 4.440892098500626e-16

ULP(100.0) = 2.8421709430404007e-14


Notes


Python math Module Python math Module