python牛顿法算立方根_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)) {returnguess

}else{

root_iter(guess, improve(guess, x), x, good_enough, improve)

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值