记录几个开平方算法

7731人阅读 评论(2)

x = 10*p + q  (1)

x^2 = 100*p^2 + 20pq + q^2 (2)

q = (x^2 - 100*p^2)/(20*p+q) (3)

3
---------------
| 12 34 56 78 90
9
---------------
|  3 34

3  q
---------------
| 12 34 56 78 90
9
---------------
6q|  3 34

3  5
---------------
| 12 34 56 78 90
9
---------------
65|  3 34
|  3 25
---------------
9 56

q = (x^2 - 4*p^2)/(4*p+q) (4)

1  0  1  0
---------------
| 1 10 01 00
1
---------------
100| 0 10
| 0 00
---------------
|   10 01
1001|   10 01
---------------
0 00

unsigned short sqrt(unsigned long a){
unsigned long rem = 0;
unsigned long root = 0;
unsigned long divisor = 0;
for(int i=0; i<16; i++){
root <<= 1;
rem = ((rem << 2) + (a >> 30));
a <<= 2;
divisor = (root<<1) + 1;
if(divisor <= rem){
rem -= divisor;
root++;
}
}
return (unsigned short)(root);
}

#include <stdio.h>
//求绝对值
#define abs(x) (x)>0?(x):(-(x))

int  main(){
double val;
double eps;
//value及精度
printf("Input $value$eps->");
scanf("%lf %lf",&val,&eps);
if(val < 0 )
{
val*=-1;
}
double low,high;
if(val  < 1)
{
low = val;
high = 1;
}
else
{
low= 1;
high = val;
}
while(1)
{
double mid =  (high + low)/2;
double tmp =  mid * mid;
if((abs(tmp-val))< eps)
{
printf("%f\n",mid);
break;
}
if(tmp > val)
{
high = mid;
}
else
{
low = mid;
}
}
}

float kamake_sqr(float number) {

long i;
float x, y;
const float f = 1.5F;
x = number * 0.5F;
y = number;
i = *(long *) &y;
i = 0x5f3759df - (i >> 1);
y = *(float *) &i;
y = y * (f - (x * y * y));
y = y * (f - (x * y * y));
return number * y;
}

main() {
printf("sqr(100)=%f", kamake_sqr(100.0));
getch();
}

5/2 = 2.5; 2.5+2/2 = 2.25; 5/2.25 = xxx; 2.25+xxx/2 = xxxx ...

1
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：1156875次
• 积分：14209
• 等级：
• 排名：第856名
• 原创：276篇
• 转载：85篇
• 译文：1篇
• 评论：698条
评论排行
最新评论