Home  >  Article  >  Backend Development  >  Python求解平方根的方法

Python求解平方根的方法

WBOY
WBOYOriginal
2016-06-06 11:22:551468browse

本文实例讲述了Python求解平方根的方法。分享给大家供大家参考。具体如下:

主要通过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)

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn