math.modf() method is a library method of math module, it is used to get the fractional part and integer part of a number. It accepts a number (integer or float) and returns a tuple that contains fractional part and integer part of the number.

```
math.modf(x)
```

`x`

− This is a numeric expression.

This method returns the fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.

The following example shows the usage of modf() method.

```
import math # This will import math module
print "math.modf(100.12) : ", math.modf(100.12)
print "math.modf(100.72) : ", math.modf(100.72)
print "math.modf(119L) : ", math.modf(119L)
print "math.modf(math.pi) : ", math.modf(math.pi)
```

**Output**

```
math.modf(100.12) : (0.12000000000000455, 100.0)
math.modf(100.72) : (0.71999999999999886, 100.0)
math.modf(119L) : (0.0, 119.0)
math.modf(math.pi) : (0.14159265358979312, 3.0)
```

```
# Importing math library
import math
# 1st type example: Taking input from user
f = float(input("Enter a float type number: "))
print("Factorial & integer part of the number is :", math.modf(f))
# 2nd type example
# Given two number, find sum of their factorial
f1 = 100.54
f2 = 13.21
# Storing factorial & integer parts
t1 = math.modf(f1)
t2 = math.modf(f2)
# printing sum of their factorial
print("Sum of factorial of ", f1, " & ", f2, " is : ", t1[0]+t2[0])
# Example type3 : When input is not a number
x = '20.4'
print(math.modf(x))
```

**Output**

```
Enter a float type number: 13.54
Factorial & integer part of the number is : (0.5399999999999991, 13.0)
Sum of factorial of 100.54 & 13.21 is : 0.7500000000000071
Traceback (most recent call last):
File "modf.py", line 22, in <module>
print(math.modf(x))
TypeError: must be real number, not str
```

In this example, we have three types of input. Firstly, we have taken an input of float type and then printed it’s factorial and integer type value. Then we have made two variables and given them value. Then we stored their factorial and integer value in the respective variables, here the value of t1 will be (0.54,100), and t2 will be (0.21,13).

Now we have printed the sum of their factorial parts, so factorial parts are stored in the 0th index of each tuple; that’s why we have printed t1[0]+t2[0].

At last type of example, we have given a character type value to x, then we have called modf() function, and we can see that it returned a TypeError.

Thanks for reading !

#python #programming

1 Likes20.00 GEEK