nextafter() function of math module in Python

Given two numbers n1 and n2 the nextafter() returns the next floating point number after n1 and before n2. If n1 and n2 are equal the function returns n2.

Math Updated 22 Aug 2021 1 min read

Overview

  • The nextafter() function in the math module of Python, returns the next floating point number after the begin and before the end.
  • If the input numbers are equal the function returns the value of the second parameter.

Example 1

python
# Example Python program that finds the next floating point number

            # between two given numbers

            import math

def printNextFloatInRange(begin, end):

                nextFloat = math.nextafter(begin, end)

                print("Next floating point number after %.16f and before %.16f:"%(begin, end))

                print(nextFloat)

# Next floating point in increasing range

            printNextFloatInRange(1, 2.1)

            printNextFloatInRange(2, 3.2)

            printNextFloatInRange(3, 4)

            printNextFloatInRange(3, 4.1)

# Next floating point in decreasing range

            printNextFloatInRange(1, 0)

Output

Output
Next floating point number after 1.0000000000000000 and before 2.1000000000000001:

1.0000000000000002

Next floating point number after 2.0000000000000000 and before 3.2000000000000002:

2.0000000000000004

Next floating point number after 3.0000000000000000 and before 4.0000000000000000:

3.0000000000000004

Next floating point number after 3.0000000000000000 and before 4.0999999999999996:

3.0000000000000004

Next floating point number after 1.0000000000000000 and before 0.0000000000000000:

0.9999999999999999