码迷,mamicode.com
首页 > 其他好文 > 详细

Exercise 1.8 牛顿法求立方根

时间:2014-09-15 17:11:19      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   strong   for   div   sp   

题目:

  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)
        }
}

 

Exercise 1.8 牛顿法求立方根

标签:style   blog   color   io   ar   strong   for   div   sp   

原文地址:http://www.cnblogs.com/linghuaichong/p/3972976.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!