python编程求一个数的平方根_用Python求一个数的平方根.

题目:

用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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值