Python modf() Function Example | Python Math Module
Python modf() is an inbuilt function that returns the fractional and integer parts of the number in the two-item tuple. Both parts have the same sign as a number. The integer part is returned as the float.
Suppose you are given two float type numbers and told to find the sum of the factorial parts of those two numbers. Here is the use of python modf() function, which is used to get factorial and integer part of a number in a tuple.
The first part is the factorial part, and the second part of the tuple is an integer part. The modf() function is under the math library, so to use this function, we first have to import the math library.
Here the x the number of which we want to find the factorial part and the integer part.
The modf() function returns factorial part and integer part of a number in a tuple of size two, where the first number is the factorial number and the second number is the integer number.
If the given number is not a number, then it returns a TypeError.
See the following example.
# app.py # 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+t2) # Example type3 : When input is not a number x = '20.4' print(math.modf(x))
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+t2.
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.