【Python】Python迭代求解开平方算法
生活随笔
收集整理的這篇文章主要介紹了
【Python】Python迭代求解开平方算法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
# 核心函數
def findSquareRoot(x):if x < 0:print ('Sorry, imaginary numbers are out of scope!')returnans = 0while ans**2 < x:ans = ans + 1if ans**2 != x:print (x, 'is not a perfect square')print ('Square root of ' + str(x) + ' is close to ' + str(ans - 1))else:print ('Square root of ' + str(x) + ' is ' + str(ans))return# 基于迭代查找在某個誤差范圍內找到平方根
def findSquareRootWithinError(x, epsilon, increment):if x < 0:print ('Sorry, imaginary numbers are out of scope!')returnnumGuesses = 0ans = 0.0while x - ans**2 > epsilon:ans += incrementnumGuesses += 1print ('numGuesses =', numGuesses)if abs(x - ans**2) > epsilon:print ('Failed on square root of', x)else:print (ans, 'is close to square root of', x)return# 基于二分查找在某個誤差范圍內找到平方根
def bisectionSearchForSquareRoot(x, epsilon):if x < 0:print ('Sorry, imaginary numbers are out of scope!')returnnumGuesses = 0low = 0.0high = xans = (high + low)/2.0while abs(ans**2 - x) >= epsilon:if ans**2 < x:low = anselse:high = ansans = (high + low)/2.0numGuesses += 1# print('low = ', low, 'high = ', high, 'guess = ', ans)print ('numGuesses =', numGuesses)print (ans, 'is close to square root of', x)return
測試代碼:
findSquareRoot(65536) findSquareRootWithinError(65535, .01, .001) findSquareRootWithinError(65535, .01, .0001) findSquareRootWithinError(65535, .01, .00001) bisectionSearchForSquareRoot(65535, .01)運行結果:
Square root of 65536 is 256 numGuesses = 255999 Failed on square root of 65535 numGuesses = 2559981 Failed on square root of 65535 numGuesses = 25599803 255.99803007005775 is close to square root of 65535 numGuesses = 24 255.99804684519768 is close to square root of 65535首先第一個函數,是迭代查找,猜想并檢查,得到的應該是相當于向下取整的結果了。
我們的測試數據是65536,得到256。
如果測試數據是65535,將得到255,然而結果顯然更接近256,這就無奈了。
第二個函數修改了while循環,遞增一個遠小于1的數字,由用戶決定誤差和每次遞增的數。
這樣可能跳過結果或者導致運行過慢。
這個函數努力規避浮點數嚴格相等判定時精度的影響。
輸出結果:
0.30000000000000004最后一個運用了二分查找(折半查找)的思想,done
總結
以上是生活随笔為你收集整理的【Python】Python迭代求解开平方算法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 洛谷P1321题题解(Java语言描述)
- 下一篇: autotools 自动编译系列简介