python中没有预定义函数的平方根

use*_*497 -2 python algorithm python-2.7

如何在不使用 python 中任何预定义函数的情况下找到数字的平方根?

我需要程序的平方根如何工作的主要逻辑。在一般数学中,我们将使用 HCF 来完成它,但在编程中,我无法找到逻辑。

Dee*_*oor 5

有一种著名的数学方法,称为Newton\xe2\x80\x93Raphson 方法,用于连续找到更好的根近似值。

\n\n

基本上,该方法采用初始值,然后在成功的迭代中收敛到解决方案。您可以在此处阅读有关它的更多信息。

\n\n

此处附上示例代码供您参考。

\n\n
def squareRoot(n):\n    x=n\n    y=1.000000 #iteration initialisation.\n    e=0.000001 #accuracy after decimal place.\n    while x-y > e:\n        x=(x+y)/2\n        y=n/x\n    print x\n\nn = input(\'enter the number : \') \nsquareRoot(n)\n
Run Code Online (Sandbox Code Playgroud)\n\n

在这里,您可以通过在 e 和 y 的小数点后添加“0”位来提高平方根结果的准确性。

\n\n

还有其他方法,例如用于查找平方根的二分搜索,如下所示

\n