math.nextafter

Full name
math.nextafter
Library
math
Syntax

math.nextafter(x, y)

Description

The math.nextafter function returns the real value closest to the number x in the direction of the number y. That is, this function returns the result of adding to the argument x the smallest possible increment in Python towards the number y.

If x is equal to y, the function returns x.

Result

The result of the math.nextafter function is a real number.

Examples

The result of adding the smallest possible increment in Python to the number 3.4 so that the result is a value closer to 8 is:

math.nextafter(3.4, 8)

3.4000000000000004

It is possible to confirm that this is the number closest to 3.4 representable in Python. For example, the number 3.4000000000000003 is rounded to the result obtained:

print(3.4000000000000003)

3.4000000000000004

If we want to obtain the closest real number to a given one towards positive infinity, we can get it with the following code:

math.nextafter(3.4, math.inf)

3.4000000000000004

If we want the result to approach negative infinity:

math.nextafter(3.4, -math.inf)

3.3999999999999995

In these examples we obtain the closest real number to one given towards zero:

math.nextafter(3.4, 0)

3.3999999999999995

math.nextafter(-3.4, 0)

-3.3999999999999995

In this other example we obtain the closest real number to a given one, moving away from zero regardless of the sign of the real number from which we start. For this we copy the sign of the number to the infinite value represented by math.inf with the math.copysign function:

a = 3.4
math.nextafter(a, math.copysign (math.inf, a))

3.4000000000000004

a = -3.4
math.nextafter(a, math.copysign (math.inf, a))

-3.4000000000000004

Submitted by admin on Sun, 01/24/2021 - 11:03