python中求平方根的方法

python中求平方根的方法

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

方法一:sqrt()函数法

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

importmath

num=10
num_sqrt=math.sqrt(num)

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

方法二:pow()函数法

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

>>>pow(12,2)#求平方
144

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

>>>

方法三:二分法

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

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)