Python 3 – modf() Method
Python is a widely used and popular programming language nowadays. This general-purpose language is efficient and has a syntax that can be easily learned by beginners. One of the mathematical functions provided by Python 3 is the modf()
method. This article will discuss what the modf()
method does and provide sample code to give a practical understanding.
Introduction to modf() Method
The modf()
method is a mathematical function in Python 3 that helps split a given floating-point number into its integer and fractional parts. It returns a tuple where the first element is the fractional part, and the second element is the integer part of the input floating-point number. The method takes a floating-point number as an argument.
The syntax of the modf()
method is as follows:
import math
math.modf( x )
Here, x
represents the input floating-point number. The returned tuple
will contain two parts separated by a comma.
Examples of the modf() Method in Action
Let’s have a look at some examples of how the modf()
method works in Python.
Example 1: Splitting Floating Point Numbers
import math
x = 5.5
fraction, integer = math.modf(x)
print("Fractional part:", fraction)
print("Integer part:", integer)
Output:
Fractional part: 0.5
Integer part: 5.0
In this example, the modf()
method was used to split the floating-point number 5.5
into its fractional and integer parts. The output clearly shows that the fractional part of 5.5
is 0.5
, and the integer part is 5.0
.
Example 2: Returning the Fraction Part of Other Numbers
import math
print("Fractional part of 8.333: ", math.modf(8.333)[0])
print("Fractional part of 19.99: ", math.modf(19.99)[0])
print("Fractional part of -0.45: ", math.modf(-0.45)[0])
Output:
Fractional part of 8.333: 0.3330000000000002
Fractional part of 19.99: 0.9899999999999993
Fractional part of -0.45: -0.44999999999999996
In this example, the modf()
method was used to return the fractional parts of other floating-point numbers. As can be seen from the output, little precision errors can occur.
Example 3: Using Only the Fractional or Integer Part
import math
x = 1.67
fraction, integer = math.modf(x)
# Using only the fractional part
print("Using only the fractional part: ", fraction)
# Using only the integer part
print("Using only the integer part: ", integer)
Output:
Using only the fractional part: 0.67
Using only the integer part: 1.0
In this example, the modf()
method was used to store the fractional part and integer part of 1.67
into separate variables. Then, we used only the fractional or integer part to demonstrate the use of each.
Conclusion
The modf()
method is useful when we need to split floating-point numbers in a Python program. It returns a tuple of the fractional and integer parts of the input floating-point number. Hopefully, this article has provided a better understanding of how the modf()
method works and how to use it in Python 3.