Nextafter() function of math module in Python

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:

# 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:

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

 


Copyright 2024 © pythontic.com