Loops are often used in programs that compute numerical results by starting with an approximate answer and iteratively improving it.

For example, one way of computing square roots is Newton’s method. Suppose that you want to know the square root of a. If you start with almost any estimate, x, you can computer a better estimate with the following formula:

For example, if a is 4 and x is 3:

Which is closer to the correct answer. If we repeat the process with the new estimate, it gets even closer:

After a few more updates, the estimate is almost the exact:

When y == x, we can stop. Here is a loop that starts with an initial estimate, x, and improves it until it stops changing:

For most values of a this works fine, but in general it is dangerous to test float equality. Floating-point values are only approximately right: most rational numbers, like 1/3 and irrational numbers, like , can’t be represented exactly with a float.

Rather than checking whether x and y are exactly equal, it is safer to use math.fabs to compute the absolute value, or magnitude, of difference between them:

If math.fabs(y-x) < something_small: break

Where something_small has a value like 0.000001 that determines how close is close enough.

Wrap this loop in a function called square_root that takes a as parameter, choose a reasonable value of x, and returns an estimate of the square root of a.

from Thinking in Python

最新文章

  1. MIT牛人解说数学体系
  2. MongoDB与.NET结合使用二(安全)
  3. JS基础学习1——什么是基础js类和原型?
  4. android之AlarmManager 全局定时器
  5. (转载)PHP_Memcache函数详解
  6. Javascript中的var_dump函数
  7. oracle中的exists 和in
  8. IE低版本兼容的感悟
  9. python -- 装饰器的高级应用
  10. 201521123055 《Java程序设计》第14周学习总结
  11. OR in Matrix
  12. 2017/11/25 2D变换
  13. java平台学习笔记
  14. HMM隐马尔科夫算法(Hidden Markov Algorithm)初探
  15. Mac无法清倒废纸篓,终极解决方案
  16. 使用python3.6和django1.9的xadmin 遇到坑,__unicode__()和__str__()
  17. 网络请求 get 请求时, 如果参数中的字符带有+号
  18. [OS] 内核态和用户态的区别
  19. EMC光纤交换机故障处理和命令分析
  20. weblogic性能监控

热门文章

  1. JQuery与CSS之图片上放置button
  2. hdu5351
  3. Spring整合Shiro从源代码探究机制
  4. [jzoj NOIP2018模拟11.02]
  5. 15-11-23:system指令
  6. js小结2
  7. 推荐几个bootstrap 后端UI框架
  8. pthread 的 api 分类
  9. SpringCloud学习笔记(6)----Spring Cloud Netflix之负载均衡-Ribbon的使用
  10. Ueditor富编辑器