• 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)
            }
    }
  • 相关阅读:
    三.Python数据类型详述
    二.Python基础语法和数据类型
    一.Python特点
    Hive之explode和lateral view
    javascript之函数作用域
    javascript之函数使用
    javascript之函数定义
    javascript之变量
    Html之元素
    Html之页面
  • 原文地址:https://www.cnblogs.com/linghuaichong/p/3972976.html
Copyright © 2020-2023  润新知