Python math.modf() 方法将数值的小数部分和整数部分作为大小为 2 的元组返回。这两部分的符号与指定的值相同。整数部分将作为浮点数检索。
元组的第一部分是小数部分,而第二部分是整数部分。
注意:这个方法不能直接访问,所以我们需要导入 math 模块。然后我们需要使用 math 静态对象调用这个方法。
语法
以下是 Python math.modf() 方法的语法 -
math.modf(x)
参数
- x − 这是一个数值表达式。
返回值
此方法返回大小为 2 的元组中 x 的小数部分和整数部分。这两个部分的符号与 x 相同。整数部分将作为浮点数检索。
示例 1
如果我们将一个正数作为参数传递给此方法,它将返回一个大小为 2 且包含正值的元组。
以下示例显示了 Python math.modf() 方法的用法。这里我们将正数作为参数传递给 modf() 方法。
# 这将导入数学模块
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)
math.modf(100.72) : (0.71999999999999886, 100.0)
math.modf(math.pi) : (0.14159265358979312, 3.0)
示例 2
如果我们将负数作为参数传递给此方法,它将返回一个大小为 2 且包含负值的元组。
在下面给出的示例中,我们创建了一个元组和一个元素列表。然后使用 modf() 方法检索 Tuples 的小数和整数部分,并在指定索引处列出元素:
# 导入数学模块
from math import modf
Tuple = (-76.43, -98.214, 35.46, 93.328)
List = [74.28, -48.38, -29.48, 95.34, 957.45]
# 对元组元素使用modf()方法
print("modf() on the first element of Tuple is: ", modf(Tuple[0]))
print("modf() on the third element of Tuple is: ", modf(Tuple[2]))
# 在列表元素上使用modf()方法
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)
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() 方法的参数。然后添加这些数字的小数部分,因为它存储在两个 Tuples 的第 0 个索引中。然后检索结果。
# 导入数学模块
import math
# 添加小数部分的modf()方法
num1 = math.modf(72.21)
num2 = math.modf(3.2)
# 打印结果
print('The addition of the given fractional part is:', num1[0]+num2[0])
以下是上述代码的输出 -
The addition of the given fractional part is: 0.4099999999999939
示例 4
如果我们将 float 值以外的任何内容传递给此方法,它将返回一个类型错误。
在下面给出的示例中,字符串值作为参数传递给 modf() 方法:
# 导入数学模块
import math
# 使用modf()方法
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
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