采用“牛顿法”求一个数的平方根

object sqrt {

  def main(args:Array[String])={
    println( sqrt(args(0).toDouble))
  }
  def sqrt(x:Double)= sqrtIter(1.0,x)
  def sqrtIter(guess:Double,x:Double):Double=
    if(isGoodEnough(guess,x)) guess
    else sqrtIter(improve(guess,x),x)

  def isGoodEnough(guess:Double, x:Double)=
    ((guess * guess -x) < 0.0001*x) && ((guess * guess -x ) > -0.0001*x)

  def improve (guess:Double, x:Double)=
    (guess+ x/guess)/2
}

我们还可以把几个辅助函数直接定义在sqrt函数里面:

object sqrt {

  def main(args:Array[String])={    println( sqrt(args(0).toDouble))  }

  def sqrt(x:Double)={    def isGoodEnough(guess:Double, x:Double)=      ((guess * guess -x) < 0.0001*x) && ((guess * guess -x ) > -0.0001*x)

    def improve (guess:Double, x:Double)=      (guess+ x/guess)/2

    def sqrtIter(guess:Double):Double=      if(isGoodEnough(guess,x)) guess      else sqrtIter(improve(guess,x))

    sqrtIter(1.0)  }}

The End......

05-08 08:07