用Python求一个数的平方根。

Ateachiteration(loop)ofthealgorithm,theapproximationxisreplacedbytheaverageofxandsdiv... 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)
展开
 我来答
zeus冰不语
2017-01-12 · 知道合伙人软件行家
zeus冰不语
知道合伙人软件行家
采纳数:37 获赞数:274
机器视觉研究生 OpenCV探索者

向TA提问 私信TA
展开全部

# -*- coding: utf-8 -*-
import math

def main(x):
x = 5
y = math.sqrt(x)
print(y)

if __name__ == "__main__":
main()

百度网友619cd53fa
2011-10-26 · TA获得超过440个赞
知道小有建树答主
回答量:201
采纳率:0%
帮助的人:259万
展开全部
下面代码定义一个函数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)
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
快乐精灵ldc
2011-10-26 · TA获得超过1.9万个赞
知道大有可为答主
回答量:2823
采纳率:100%
帮助的人:2247万
展开全部
import math
math.sqrt()
或者
num**0.5
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
jaybestwang
2011-10-25 · TA获得超过4106个赞
知道小有建树答主
回答量:940
采纳率:0%
帮助的人:700万
展开全部
import math
x = s
while math.fabs(x*x - s)>=0.0000001:
x = (x + s/x)/2.0
print x, x*x
追问
要用 def heron(s):  额
追答
def herons(s):
import math
x = s
while math.fabs(x*x - s) >= 0.0000001:
x = (x + s/x)/2.0
print x, x*x
不就加个函数头么????
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(2)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式