標籤:python 日記
演算法如下:
1.猜測一個要求數位平方根
2.用 原數 / 猜測數字
3.用 計算步驟2的值與猜測數位平均值
4.步驟3得到的值為新的猜測值
5.判斷新的猜測值和原猜測值是否相同,相同則跳轉至步驟2,不同則該猜測值為原數平方根
# 在電腦中相同與不同,參考浮點數相同方法
python源碼如下:
import math
from math import fabs
num_be = input("Please enter number use to solve square")
while(not num_be.isdigit()): #保證輸入的為整數
print("please enter number")
num_be = input("Please enter number use to solve square")
num_float = float (num_be)
guess = input("please enter guess number")
while(not guess.isdigit()): #保證輸入的為整數
print("please enter number")
guess = input("please enter guess number")
guess_float = float (guess)
precision = float (input("please enter the precision"))
count = 0 #記錄迴圈多少次
befor = 0 #前一個猜測值
sum =0
while(fabs(guess_float - befor) > precision): #使用絕對值防止,出現負值小於precision的情況
befor = guess_float
guess_float = ((num_float / guess_float) + guess_float) / 2
count += 1
print("use count : ",count)
print("THe ",num_float,"square is :", guess_float)
Python 例題 -- 巴比倫平方根演算法