Python提供了計算數字冪的函數,因此可以簡化計算數字冪的任務。它在日常編程中具有許多應用程序。
天真的計算能力的方法:
# Python code to demonstrate naive method
# to compute power
n = 1
for i in range(1,5):
n=3*n
print ("The value of 3**4 is:",end="")
print (n)
輸出:
The value of 3**4 is:81
使用pow()
1. float pow(x,y):此函數計算x ** y。此函數首先將其參數轉換為float,然後計算冪。
Declaration: float pow(x,y) 參數: x: Number whose power has to be calculated. y: Value raised to compute power. 返回值: Returns the value x**y in float.
# Python code to demonstrate pow()
# version 1
print ("The value of 3**4 is:",end="")
# Returns 81
print (pow(3,4))
輸出:
The value of 3**4 is:81.0
2. float pow(x,y,mod):此函數計算(x ** y)%mod。此函數首先將其參數轉換為float,然後計算冪。
Declaration: float pow(x,y,mod) 參數: x: Number whose power has to be calculated. y: Value raised to compute power. mod: Value with which modulus has to be computed. 返回值: Returns the value (x**y) % mod in float.
# Python code to demonstrate pow()
# version 2
print ("The value of (3**4) % 10 is:",end="")
# Returns 81%10
# Returns 1
print (pow(3,4,10))
輸出:
The value of (3**4) % 10 is:1
pow()中的實現案例:
# Python code to discuss negative
# and non-negative cases
# positive x, positive y (x**y)
print("Positive x and positive y:",end="")
print(pow(4, 3))
print("Negative x and positive y:",end="")
# negative x, positive y (-x**y)
print(pow(-4, 3))
print("Positive x and negative y:",end="")
# positive x, negative y (x**-y)
print(pow(4, -3))
print("Negative x and negative y:",end="")
# negative x, negative y (-x**-y)
print(pow(-4, -3))
輸出:
Positive x and positive y:64 Negative x and positive y:-64 Positive x and negative y:0.015625 Negative x and negative y:-0.015625
相關用法
注:本文由純淨天空篩選整理自 pow() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。