python中求平方根的方法

Python (196) 2023-07-17 23:39:53

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

方法一:sqrt()函数法

python中sqrt()函数可以获取数字的平方根,是查找平方根的预定义方法,须导入matn模块才能使用。

纯文本
复制到剪贴板
在新窗口中打开代码
EnlighterJS 3 Syntax Highlighter
importmath
num=10
num_sqrt=math.sqrt(num)
print(f'{num}squarerootis{num_sqrt}')
importmath num=10 num_sqrt=math.sqrt(num) print(f'{num}squarerootis{num_sqrt}')
importmath

num=10
num_sqrt=math.sqrt(num)

print(f'{num}squarerootis{num_sqrt}')

方法二:pow()函数法

pow()也是一种预定义方法,用于找出数字的幂,它以两个参数作为输入,第一个是数字本身,第二个是该数字的幂。

纯文本
复制到剪贴板
在新窗口中打开代码
EnlighterJS 3 Syntax Highlighter
>>>pow(12,2)#求平方
144
>>>pow(144,.5)#求平方根
12.0
>>>
>>>pow(12,2)#求平方 144 >>>pow(144,.5)#求平方根 12.0 >>>
>>>pow(12,2)#求平方
144

>>>pow(144,.5)#求平方根
12.0

>>>

方法三:二分法

二分法是python中求平方根的经典求法

纯文本
复制到剪贴板
在新窗口中打开代码
EnlighterJS 3 Syntax Highlighter
x=int(input())
low,high,ans=0,x,-1
whilelow<=high:
mid=(low+high)//2
ifmid*mid<=x:
ans=mid
low=mid+1
else:
high=mid-1
print(ans)
x=int(input()) low,high,ans=0,x,-1 whilelow<=high: mid=(low+high)//2 ifmid*mid<=x: ans=mid low=mid+1 else: high=mid-1 print(ans)
x=int(input())
low,high,ans=0,x,-1
whilelow<=high:
mid=(low+high)//2
ifmid*mid<=x:
ans=mid
low=mid+1
else:
high=mid-1
print(ans)

以上就是python中求平方根的几种方法,大家可以选择自己喜欢的方式去求取哟~

THE END

发表回复