modf(n)
Retuns a tuple having two float data type elements , (fractional_part, integer_part)
import math
d=math.modf(23.45)
print(type(d)) #<class 'tuple'>
print(d[0]) # 0.4499999999999993
print(d[1]) # 23.0
import math
print(math.modf(23.45)) # (0.4499999999999993, 23.0)
print(math.modf(23)) # (0.0,23.0)
print(math.modf(-12.34))# (-0.33999999999999986, -12.0)
Using PI to get whole and fraction parts
import math
print(math.modf(math.pi)) # (0.14159265358979312, 3.0)
The whole part of the input number is always float data type. To get the integer we can use math.floor().
print(math.floor(23.45)) # 23
Clarification: The math.modf() function returns a tuple containing the fractional and integer parts of a number, both as floats, even if the integer part has no decimals.
import math
print(math.modf(23.45)) # (0.4499999999999993, 23.0)
print(math.modf(23)) # (0.0, 23.0)
print(math.modf(-12.34)) # (-0.33999999999999986, -12.0)
math.modf() is useful in breaking down numbers for scientific or financial calculations where fractional and whole numbers need to be processed separately.
For example:
fractional_part, integer_part = math.modf(123.456)
print(f"Fractional: {fractional_part}, Integer: {integer_part}")
Output
Fractional: 0.45600000000000307, Integer: 123.0
This function ensures easy separation of floating-point data in cases where both parts are required.