温馨提示×

python如何计算幂函数

九三
1422
2021-02-18 09:25:22
栏目: 编程语言

python如何计算幂函数

在python中使用pow函数计算幂函数,具体方法如下:

pow:pow()函数的作用是用于计算 x 的 n 次幂函数,其中n为整数。

pow()函数使用方法:

class Solution:

def myPow(self, x: float, n: int) -> float:

# x为大于0的数,因为负数无法开平方(不考虑复数情况)

if x>1:

low,high = 0,x

else:

low,high =x,1

while True:

r = (low+high)/2

judge = 1

for i in range(n):

judge *= r

if x >1 and judge>x:break # 对于大于1的数,如果当前值已经大于它本身,则无需再算下去

if x <1 and judgeif abs(judge-x)<0.0000001: # 判断是否达到精度要求

print(pow(x,1/n)) # pow函数计算结果

return r

else:

if judge>x:

high = r

else:

low = r

0