日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

【Python】Python迭代求解开平方算法

發(fā)布時間:2025/3/15 python 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Python】Python迭代求解开平方算法 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
# 核心函數(shù) 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

首先第一個函數(shù),是迭代查找,猜想并檢查,得到的應該是相當于向下取整的結果了。
我們的測試數(shù)據(jù)是65536,得到256。
如果測試數(shù)據(jù)是65535,將得到255,然而結果顯然更接近256,這就無奈了。

第二個函數(shù)修改了while循環(huán),遞增一個遠小于1的數(shù)字,由用戶決定誤差和每次遞增的數(shù)。
這樣可能跳過結果或者導致運行過慢。
這個函數(shù)努力規(guī)避浮點數(shù)嚴格相等判定時精度的影響。

print(0.1+0.2)

輸出結果:

0.30000000000000004

最后一個運用了二分查找(折半查找)的思想,done

總結

以上是生活随笔為你收集整理的【Python】Python迭代求解开平方算法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。