Created
July 22, 2013 03:00
-
-
Save GZShi/6051054 to your computer and use it in GitHub Desktop.
二分搜索开平方
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <math.h> | |
double m_abs(double num) | |
{ | |
return (num < 0 ? -num : num); | |
} | |
double bsqrt(double begin, double end, double value, double precision) | |
{ | |
// if(begin <= end) | |
// return 0; | |
double mid = begin + (end - begin) / 2.0; | |
double temp = mid * mid; | |
if(m_abs(temp - value) <= precision) | |
return mid; | |
else if(mid * mid > value) | |
return bsqrt(begin, mid, value, precision); | |
else | |
return bsqrt(mid, end, value, precision); | |
} | |
double m_sqrt(double n) | |
{ | |
if(n > 0) | |
return bsqrt(0, n, n, 0.00000001); | |
else if(m_abs(n) <= 0.00000001) | |
return 0; | |
else | |
return 0; | |
} | |
int main(void) | |
{ | |
int i = 0; | |
for(i = 0; i <= 100; ++i) | |
{ | |
printf("m_sqrt(%d) = %f, sqrt(%d) = %f\n", i, m_sqrt(i), i, sqrt(i)); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment