算法如下:
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)