二分法实现数字的开方运算
2011-07-08 21:17
211 查看
今天闲着,听了mit的计算机编程课程后,写了一个实现开平方的算法,主要也体现了二分法的思想,每次迭代让问题规模减半.
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
using namespace std;
int main(){
double a = 8.0;
int c = 1000;
double low = 0.1;
double high = 10.0;
double guess = (low+high)/2;
while(c>=0&&fabs(guess*guess-a)>0.001){
if(guess*guess<a)
{
low = guess;
}
else
{
high = guess;
}
guess = (low+high)/2;
c--;
}
printf("%f\n",guess);
printf("%d\n",c);
return 1;
}
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
using namespace std;
int main(){
double a = 8.0;
int c = 1000;
double low = 0.1;
double high = 10.0;
double guess = (low+high)/2;
while(c>=0&&fabs(guess*guess-a)>0.001){
if(guess*guess<a)
{
low = guess;
}
else
{
high = guess;
}
guess = (low+high)/2;
c--;
}
printf("%f\n",guess);
printf("%d\n",c);
return 1;
}
相关文章推荐
- 巧用二分法实现数学开方(sqrt)运算
- 程序员面试100题(算法)之找出数组中两个只出现一次的数字(位运算实现)
- 用异或运算实现两个数字的交换(装x)
- 实现计算器4则运算算法-分离算法 - 实践 (上) 符号和数字分离
- php实现的数字验证码及数字运算验证码
- Js中实现日期加减--字符串转换成数字进行运算
- java实现简单的数字运算以及dos命令运行Java程序
- javascript 闭包应用, 阿隆佐·邱奇想法——计算机实现运算,而不需要0、1、2、3这些数字和+、-、*、/这些符号。
- 怎么用BigDecimal实现大数字运算?
- C#实现大数字的运算
- php实现的数字验证码及数字运算验证码
- 每天一道LeetCode-----重新实现开方运算sqrt(x),只返回整数部分即可
- C#实现数字字符串的加法和自增运算
- 位运算实现输出数字的二进制
- java实现大数字的运算
- 如果系统要使用超大整数(超过long长度范围),请你设计一个数据结构来存储这种超大型数字以及设计一种算法来实现超大整数加法运算)
- 面试算法题:不用+、-、×、÷数字运算符做加法 (位运算实现加法操作)
- java 实现二分法查找出数组重复数字
- 二分法实现开方
- 6.5 旋转数组的最小数字(二分法:python,java实现)