Exercise 1.8 牛顿法求立方根

题目:

  Newton's method for cube roots is based on the fact that if y is an approximation to the cube root of x, then a better approximation is given by the value: (r/(y*y)+2*y)/3. Use this formula to implement a cube-root procedure analogous to the square-root procedure. (In section 1.3.4 we will see how to implement Newton's method in general as an abstraction of these square- root and cube-root procedures.)

-------------------------------------------------------------------------------------------------------------------------------------------------------------------

牛顿法求平方根、立方根,实际上拥有共同的概念元素:

  1. 前一个逼近值(previous guess)

  2. 当前逼近值(current guess)

  3. 目标值(x)

  4. 判断当前逼近值是否已经足够好(good_enough)

  5. 根据x和current guess求出下一个逼近值(improve_guess)

平方根、立方根的唯一差异在于improve_guess的具体实现,即题目中黑体加粗的求值公式。

平方根:

def improve_sqrt(guess: Double, x: Double): Double = {
        return (x / guess + guess) / 2
}

立方根:

def improve_cubert(guess:Double, x:Double):Double={
        return (x/(guess*guess)+2*guess)/3
}

计算引擎是:

def root_iter(prev_guess: Double,
                  guess: Double,
                  x: Double,
                  good_enough: (Double, Double, Double) => Boolean,
                  improve:(Double,Double)=>Double): Double = {
        if (good_enough(prev_guess, guess, x)) {
            return guess
        } else {
            root_iter(guess, improve(guess, x), x, good_enough, improve)
        }
}

 

posted on 2014-09-15 15:50  一生只想往前飞  阅读(474)  评论(0编辑  收藏  举报

导航