题目:
用Python求一个数的平方根.
At each iteration (loop) of the algorithm,the approximation x is replaced by the average of x and s divided by x.Written as an assignment statement,it looks like this:
x = (x + s/x)/2.0.There are various criteria for deciding when to stop improving the answer of a square root algorithm.In your implementation,I want you keep looping until the square of x is very close to the value of s.In other words,you want to reduce the error of your approximation x until it is acceptably small.You can measure the relative error by comparing the absolute difference of x squared and s.This is written mathematically as:
error = | x * x – s |.Use the math.fabs() function to compute absolute value.
So keep looping and calculating better and better values for x until the error is less than some small constant.For
your implementation of heron(s),stop when error < 0.0000001 which is a small discrepancy.Add a print
statement inside your algorithm loop which prints out both x and x*x at each step so you can see how fast it converges to a good answer.It is very interesting to watch it work.Try different starting guess values for x and see if it
makes any difference to the number of loops required (always use a positive guess value)
解答:
下面代码定义一个函数heron(s)用迭代的方法取得平方根,其中x=s/2可以使用x=s/3,s/5之类的多个值实验一下,看分别需要多少步.
以s=500为例,
x=s时需要9步
x=s/2时需要8步
x=s/3时需要7步
x=s/5时需要5步
”’
Created on 2011-10-26
@author:legendxx
”’
import math
def heron(s):
x=s/2
count=0
sqr=x*x
while math.fabs(sqr – s)>=0.0000001:
count+=1
x = (x + s/x)/2.0
sqr=x*x
print count,”:”,x,sqr
print count,”steps needed”
if __name__ == ‘__main__’:
s=float(raw_input(“input a number”))
heron(s)