Python math.modf() 方法



Python math.modf() 方法将数值的小数部分和整数部分作为大小为 2 的元组返回。这两部分与指定值的符号相同。整数部分作为浮点数检索。

元组的第一部分是小数部分,第二部分是整数部分。

注意:此方法无法直接访问,因此我们需要导入math 模块。然后我们需要使用 math 静态对象调用此方法。

语法

以下是Python math.modf()方法的语法:

math.modf(x)

参数

  • x − 这是一个数值表达式。

返回值

此方法返回 x 的小数部分和整数部分,作为一个大小为 2 的元组。这两部分与 x 的符号相同。整数部分作为浮点数检索。

示例 1

如果我们将正数作为参数传递给此方法,它将返回一个包含正值的大小为 2 的元组。

以下示例显示了 Python math.modf() 方法的用法。这里我们将正数作为参数传递给 modf() 方法。

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

运行上述程序时,会产生以下结果:

math.modf(100.12) :  (0.12000000000000455, 100.0)
math.modf(100.72) :  (0.71999999999999886, 100.0)
math.modf(math.pi) :  (0.14159265358979312, 3.0)

示例 2

如果我们将负数作为参数传递给此方法,它将返回一个包含负值的大小为 2 的元组。

在下面给出的示例中,我们创建了一个元组和一个包含元素的列表。然后使用 modf() 方法检索元组和列表中指定索引处的元素的小数部分和整数部分

# importing the math module
from math import modf
Tuple = (-76.43, -98.214, 35.46, 93.328)
List = [74.28, -48.38, -29.48, 95.34, 957.45]
# Using modf() method on tuple elements
print("modf() on the first element of Tuple is: ", modf(Tuple[0]))
print("modf() on the third element of Tuple is: ", modf(Tuple[2]))
# Using modf() method on list elements
print("modf() on the third element of list is: ", modf(List[2]))
print("modf() on the fifth element of list is: ", modf(List[4]))

执行上述代码时,我们将获得以下输出:

modf() on the first element of Tuple is:  (-0.4300000000000068, -76.0)
modf() on the third element of Tuple is:  (0.46000000000000085, 35.0)
modf() on the third element of list is:  (-0.4800000000000004, -29.0)
modf() on the fifth element of list is:  (0.4500000000000455, 957.0)

示例 3

在这里,两个浮点数作为参数提供给 modf() 方法。然后将这些数字的小数部分相加,因为它存储在两个元组的第 0 个索引中。然后检索结果。

# importing the math module
import math
# modf() method to add fractional part
num1 = math.modf(72.21)
num2 = math.modf(3.2)
# printing the result
print('The addition of the given fractional part is:', num1[0]+num2[0])

以下是上述代码的输出:

The addition of the given fractional part is: 0.4099999999999939

示例 4

如果我们将浮点值以外的任何值传递给此方法,它将返回类型错误。

在下面给出的示例中,字符串值作为参数传递给 modf() 方法

# importing the math module
import math
# Using modf() method
print("The output is: ", math.modf('63.29'))

上述代码的输出如下:

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 4, in <module>
    print("The output is: ", math.modf('63.29'))
TypeError: must be real number, not str
python_maths.htm
广告