modf()函數是Python中的內置函數,它返回two-item元組中數字的小數和整數部分。兩個部分的符號與數字相同。整數部分以浮點數形式返回。
用法:
modf(number)
參數:
There is only one mandatory parameter which is the number.
返回值:
此方法返回two-item元組中數字的小數和整數部分。兩個部分的符號與數字相同。整數部分以浮點數形式返回。
異常:
TypeError: If anything other then a float number is passed, it returns a type error.
下麵是modf()方法的Python3實現:
代碼#1
# Python3 program to demonstrate the function modf()
# This will import math module
import math
# modf() function used with a positive number
print("math.modf(100.12):", math.modf(100.12))
# modf() function used with a negative number
print("math.modf(-100.72):", math.modf(-100.72))
print("math.modf(2):", math.modf(2))
輸出:
math.modf(100.12): (0.12000000000000455, 100.0) math.modf(-100.72): (-0.7199999999999989, -100.0) math.modf(2): (0.0, 2.0)
代碼2:TypeError
# Python3 program to demonstrate the
# error in function modf()
# This will import math module
import math
# modf() function used with a positive number
print("math.modf(100.12):", math.modf("100.12"))
輸出:
Traceback (most recent call last): File "/home/fa6d7643de17bafe9a0e0693458e4bdb.py", line 9, in print("math.modf(100.12):", math.modf("100.12")) TypeError:a float is required
代碼#3:
# Python3 program to demonstrate the
# error in function modf()
# This will import math module
from math import modf
lst = [3.12, -5.14, 13.25, -5.21]
tpl = (33.12, -15.25, 3.15, -31.2)
# modf() function on elements of list
print("modf() on First list element:", modf(lst[0]))
print("modf() on third list element:", modf(lst[2]))
# modf() function on elements of tuple
print("modf() on Second tuple element:", modf(tpl[1]))
print("modf() on Fourth tuple element:", modf(tpl[3]))
輸出:
modf() on First list element: (0.1200000000000001, 3.0) modf() on third list element: (0.25, 13.0) modf() on Second tuple element: (-0.25, -15.0) modf() on Fourth tuple element: (-0.1999999999999993, -31.0)
實際應用:
給定兩個浮點數,將小數部分相乘並返回答案。
代碼4:
# Python3 program to demonstrate the
# application of function modf()
# This will import math module
import math
# modf() function to multiply fractional part
a = math.modf(11.2)
b = math.modf(12.3)
# Multiply the fractional part as is stored
# in 0th index of both the tuple
print(a[0]*b[0])
輸出:
0.05999999999999993
相關用法
- Python math.gcd()用法及代碼示例
- Python math.cos()用法及代碼示例
- Python math.tan()用法及代碼示例
- Python math.sin()用法及代碼示例
- Python math.ceil()用法及代碼示例
- Python math.factorial()用法及代碼示例
- Python math hypot()用法及代碼示例
- Python math copysign()用法及代碼示例
- Python math sqrt()用法及代碼示例
- Python math.copysign()用法及代碼示例
- Python math.floor()用法及代碼示例
- Python math.fabs()用法及代碼示例
- Python math gamma()用法及代碼示例
- Python math.comb()用法及代碼示例
- Python math.perm()用法及代碼示例
注:本文由純淨天空篩選整理自Striver大神的英文原創作品 Python math function | modf()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。