If you are given two float type numbers and told to find the sum of the factorial parts of those two numbers. Here is the python modf() function, which is used to get factorial and integer parts 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.
Python modf()
Python modf() is a built-in 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.
Syntax
modf(x)
Arguments
Here the x is the number we want to find the factorial part and the integer part.
Return Value
The modf() function returns the 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.
Programming Examples
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[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.