你知道怎么改進Python 二分法和牛頓迭代法求算術平方根嗎
二分法
def sqrtb(n): if n<0: raise ValueError('n>=0') left,right,x=0,n,n/2 while not -1e-15<x*x-n<1e-15: if x*x>n: right,x = x,left+(x-left)/2 else: left,x = x,right-(right-x)/2 return x
求最接近算術平方根的整數(shù)
def sqrtB(x): if x==0: return 0 #y,x=x,round(x) left,right,ret = 1,x,0 while left<=right: mid = left + (right-left)//2 if mid<x/mid: left = mid+1 ret = mid elif mid==x/mid: ret = mid break else: right = mid-1 return ret
>>> sqrtB(9)
3
>>> sqrtB(8)
2
>>> sqrtB(9.2)
3.0
>>> sqrtB(7.8)
2.0
>>> sqrtB(4)
2
>>>
二分法原理
牛頓迭代法
def sqrtn(n): if n<0: raise ValueError('n>=0') x = n/2 while not -1e-15<x*x-n<1e-15: x = (x+n/x)/2 return x
一點小改進:不用1e-15來比較
def sqrt2(n): x = n while x*x>n: x = (x+n/x)/2 return x
缺點:碰到n=7,13,...等,會進入死循環(huán)
增加判斷跳出循環(huán):
def sqrt(n): x = n while x*x>n: y,x = x,(x+n/x)/2 if y==x: break return x
# sqrt(n) n=1~25的精度測試:
0.0
-2.220446049250313e-16
0.0
0.0
0.0
0.0
0.0
-4.440892098500626e-16
0.0
-4.440892098500626e-16
0.0
0.0
4.440892098500626e-16
0.0
0.0
0.0
0.0
8.881784197001252e-16
-8.881784197001252e-16
0.0
0.0
0.0
0.0
0.0
0.0
>>>
牛頓迭代法原理
從函數(shù)意義上理解:要求函數(shù)f(x)=x²,使f(x)=num的近似解,即x²-num=0的近似解。
從幾何意義上理解:要求拋物線g(x)=x²-num與x軸交點(g(x)=0)最接近的點。
假設g(x0)=0,即x0是正解,讓近似解x不斷逼近x0,x0 ~ x - f(x)/f'(x)
def cubeN(n): x,y = n/3,0 while not -1e-15<x-y<1e-15: y,x = x,(2/3)*x+n/(3*x*x) return x ''' >>> cubeN(27) 3.0 >>> cubeN(9) 2.080083823051904 >>> '''
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注本站的更多內容!
版權聲明:本站文章來源標注為YINGSOO的內容版權均為本站所有,歡迎引用、轉載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。