不用库函数 求解立方根

题目:

如标题所示,不用平方根库函数,求解一个数字的平方根。

分析:

这个问题有两个思路:

思路1:采用二分的方式(无处不在的二分),上界初始化为数字本身,下界初始化为1,这样用二分,判断中间数字的平方和目标数字比较,再修改上界和下界,直到小于一定的阈值。

思路2:采用牛顿法(数值分析中提到),采用微分的方式,从初始点开始,每次迭代,微分求解切线,然后求解切线和x轴的交点,再以这个交点作为起点,迭代进行。比如求解24,那么写出函数:

f(x) = x^2 - 24

我们目标就是求解这个函数的根,函数一阶导数是:

f'(x) = 2*x

起始点可以选择x0 = 24,通过求解,可以得到下一个迭代点的公式为:

x1 = -f(x0) / f'(x0) + x0

这样迭代下去,直到最后小于一定的阈值。

算法代码如下:

[cpp]  view plain copy
  1. <span style="font-size:18px;">/* 
  2.  * square.cpp 
  3.  * 
  4.  *  Created on: 2012-10-4 
  5.  *      Author: happier 
  6.  */  
  7.   
  8.   
  9. #include <iostream>  
  10. #include <algorithm>  
  11. #include <cstdlib>  
  12. using namespace std;  
  13. #define E 0.001<span>       </span>//精度设置  
  14.   
  15. /* 
  16.  * 二分法求解 
  17.  */  
  18. double bSearch(double number, int *count)  
  19. {  
  20.     //int count = 0;  
  21.     double start = 1.0;  
  22.     double end = number;  
  23.     while(true)  
  24.     {  
  25.         (*count)++;  
  26.         double mid = (start + end) / 2;  
  27.         if(mid * mid - number <= E && mid * mid - number >= -E)  
  28.             return mid;  
  29.   
  30.         if(mid*mid - number > E)  
  31.             end = mid;  
  32.         else  
  33.             start = mid;  
  34.     }  
  35.   
  36.     return 0;  
  37. }  
  38.   
  39. /* 
  40.  * 牛顿法求解 
  41.  */  
  42. double newton(double number, int *count)  
  43. {  
  44.     double x0 = number;  
  45.     double x1;  
  46.     while(true)  
  47.     {  
  48.         (*count)++;  
  49.         x1 = -(x0*x0 - number) / (2 * x0) + x0;  
  50.         if(x1 * x1 - number <= E && x1 * x1 - number >= -E)  
  51.             return x1;  
  52.         x0 = x1;  
  53.     }  
  54.   
  55.     return 0;  
  56. }  
  57.   
  58. int main()  
  59. {  
  60.     int count = 0;  //统计迭代次数  
  61.     cout << "Please input the number::" << endl;  
  62.     double number;  
  63.     cin >> number;  
  64.   
  65.     cout << bSearch(number, &count) <<endl;  
  66.     cout << count <<endl;  
  67.   
  68.     count = 0;  
  69.     cout << newton(number, &count) <<endl;  
  70.     cout << count <<endl;  
  71.   
  72.     return 0;  
  73. }</span>  

总结:

通过运行发现,牛顿法的求解速度要比二分法快很多,例如求解30000,牛顿法只要11次迭代,可以达到0.001精度,但是二分法需要33次,所以数值分析普遍采用牛顿法进行求根。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值