【问题标题】:square root without pre-defined function in pythonpython中没有预定义函数的平方根
【发布时间】:2018-02-21 07:23:30
【问题描述】:

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

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

【问题讨论】:

标签: python algorithm python-2.7


【解决方案1】:

以下python实现基于C++ implementation。代码没有直接使用sqrt,而是使用math.frexpmath.ldexp来计算sqrt。这种算法和其他算法一样适合训练。在专业设置中最好使用math.sqrt,因为该功能使用直接Intel instructionARM64 instruction

import math
def sqrt(n):
    if n < 0:
        raise ArithmeticError()
    n, exp = math.frexp(n)
    if (exp & 1):
        exp -= 1
        n *= 2
    y = (1 + n) / 2
    z = 0
    while (y != z):
        z = y
        y = ( y + n/y) / 2
    return math.ldexp(y, int(exp/2))


import unittest

class TestSqrt(unittest.TestCase):

    def test_simple(self):
        self.assertEqual(sqrt(4), math.sqrt(4))

    def test_various(self):
        l = [4, 9, 64, 49, 39499, 48484]
        for i in l:
            self.assertEqual(sqrt(i), math.sqrt(i))


if __name__ == '__main__':
    unittest.main()

【讨论】:

    【解决方案2】:

    有一种著名的数学方法,称为 Newton-Raphson 方法,用于逐次找到根的更好近似值。

    基本上,这个方法取初始值,然后在成功的迭代中收敛到解决方案。你可以阅读更多关于它here

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

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

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

    还有其他方法,如二分查找,如 here 所示。

    【讨论】:

      【解决方案3】:

      这对我有用:

      def sqrt(n):
          for i in range(1, n+1):
              if (n % i == 0) and (i * i == n):
                  return i
                  break
      

      基本上程序从 1 到 n 运行 for 循环,然后检查是否 n % i = 0 和 i squared = n,如果为真 - 返回 i 并中断。

      【讨论】:

        【解决方案4】:

        这是您可以做到的一种方法。请注意,这不是数学上最有效的方法,它只是一种简单的方法,不会弄乱奇怪的数学:

        a=int(input('number! '))
        accuracy=10 #number of decimals
        s=0
        step=1
        for i in range(accuracy+1):
            while (s+step)**2<=a:
                s+=step
            step=step/10
        s=format(s,'.'+str(accuracy)+'f')
        print(s)
        

        【讨论】:

          【解决方案5】:

          我会通过构建一个可以给出精确猜测的算法来解决这个问题,因为这些步骤很容易理解并且可以重复直到非常准确。例如:

          • 在已知的完美正方形中构建(2^2 是 4,4^2 是 16,等等)
          • 找出给定数字介于哪个完全平方之间(如果给定 10,则它介于 3^2 (9) 和 4^2 (16) 之间)。因此,10 的平方根介于 3 和 4 之间。

          查看this link for an easy explanation 这个算法以及如何重复以确保准确性。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-03-04
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多