search

Home  >  Q&A  >  body text

Python求解平方根的代码怎么写?

Python求解平方根的代码怎么写?

baby不要哭泣baby不要哭泣2826 days ago2255

reply all(2)I'll reply

  • 数据分析师

    数据分析师2017-10-01 00:39:34

    How to write the code to solve the square root in Python? -PHP Chinese website Q&A-How to write the code to solve the square root in Python? -PHP Chinese website Q&A

    Let’s take a look and learn.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-03-03 10:48:09

    主要通过SICP的内容改写而来。基于newton method求解平方根。代码如下:

    #!/usr/bin/python
    def sqrt_iter(guess,x):
      if(good_enough(guess, x)):
        print guess
      else:
        sqrt_iter(improve(guess, x),x)
    def improve(guess, x):
      return average(guess, x/guess)
    def average(x,y):
       return (x+y)/2
    def good_enough(guess,x):
      if(abs(guess * guess -x) < 0.0001):
        return True
      else:
        return False
    def sqrt_oliver(x):
      sqrt_iter(1.0,x)
    sqrt_oliver(5)


    reply
    0
  • Cancelreply