解释这个Python代码的逻辑和含义。 [英] Explain the logic and meaning of this Python code.

查看:115
本文介绍了解释这个Python代码的逻辑和含义。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

x = 25
epsilon = 0.01
step = epsilon**2
numGuesses = 0
ans = 0.0

while (abs(ans**2 - x)) >= epsilon and ans <= x:
    ans += step
    numGuesses += 1

print('numGuesses = ' + str(numGuesses))

if abs(ans**2-x) >= epsilon:
    print('Failed on square root of ' + str(x))

else:
    print(str(ans) + ' is close to the square root of ' + str(x))





我尝试了什么:



这个程序如何确定平方根?

答:我明白了。它将x减小一个小值,即0.0001,即步骤直到x小于epsilon。 ans由ans + = step递增。因此,当它达到大于或等于x的值时,循环终止。



我不确定我写的这个ans,告诉我这是对还是



What I have tried:

How does this program determine the square root?
Ans: I understood it. It reduces x by a small value i.e. 0.0001 i.e. step until x is less than epsilon. ans is incremented by ans += step. So when it reaches to the value greater than or equal to x, loop terminates.

I am not sure about this ans I wrote, tell me is this right or wrong

推荐答案

怎么了?整个想法。你使用epsilon = 0.01并写下使用0.0001。很好,然后尝试找到一个不是25的平方根,但是从0.000025,看看会发生什么。当然,您可以减少epsilon,使其成为一小部分输入值,但无论如何都无法获得任何可接受的准确度。有两个原因:1)你只增加你的回答 ans ,永不减少,2)你使用固定步骤,也就是说,在你的迭代中,准确性每次迭代都不被采用为 ans ** 2 接近输入值。



你甚至做过没有定义用于计算根的任何函数。



这是有用的:计算平方根的方法



-SA
What's wrong? The whole idea. You use epsilon = 0.01 and write about the use of 0.0001. Fine, then try to find a square root not from 25, but from 0.000025 and see what happens. Of course, you can reduce epsilon, to make it a small fraction input value, but you cannot get any acceptable accuracy anyway. Two reasons for that are: 1) you only increase your "answer" ans, never decrease, 2) you use fixed step, that is, in your iterations, the accuracy of each iteration is not adopted as ans**2 gets closer to the input value.

And you even did not define any function for calculation of the root.

This is what works: Methods of computing square roots.

—SA


引用:

答:我明白了。它将x减小一个小值,即0.0001,即步骤直到x小于epsilon。 ans由ans + = step递增。因此,当它达到大于或等于x的值时,循环终止。

Ans: I understood it. It reduces x by a small value i.e. 0.0001 i.e. step until x is less than epsilon. ans is incremented by ans += step. So when it reaches to the value greater than or equal to x, loop terminates.

错误。

此程序通过尝试每个可能的 ans x 的平方根c $ c>按顺序从 0 开始,并以小值 0.0001 递增。

在每个循环中,将实际 ans 的平方与 x 进行比较,直到差值小于 epsilon ans 小于 x



这个方法很天真,有很多问题。

- 它很慢,很慢,很慢。

- for x 大于 10000 ,你开始找到 ans 的值在 epsilon 容差范围内。

Wrong.
This program search for the square root of x by trying every possible ans in sequence starting at 0 and incrementing with a small value 0.0001 .
On every loop, the square of actual ans is compared to x until the difference is less than epsilon and ans is less that x.

The method is very naive and have many problems.
- it is slow, very slow, waaay slow.
- for x greater than 10000, you start to find values where ans never comes within the epsilon tolerance.


这篇关于解释这个Python代码的逻辑和含义。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆