python如何计算幂函数

992
2021/2/18 9:25:22
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: python字符串处理与应用的方法有哪些