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
廣告