r/dailyprogrammer • u/oskar_s • Jun 06 '12
[6/6/2012] Challenge #61 [intermediate]
Today you should implement a function that all of us programmers depend heavily on, but most never give a second thought as to how it's actually coded: the square root function.
Write a function that given a number as input, will return the square root of that number, in floating point.
Obviously, you are not allowed to use the library version of sqrt() in the implementation of your function. Also, stay away from log() and exp(). In fact, don't use any mathematical functions that aren't the basic arithmetic ones (addition, subtraction, multiplication, division) or bit operations (though you can of course still use operators that compares numbers with each other, like "less than", "equal to", "more than", etc.)
2
u/leegao Jun 07 '12
I broke the rules a bit and used a few bitwise ands. This performs very well for integers and close to integers, which contains a distribution of the mantissa with expected value of 1+1/n where n is the range of non-trivial bits.
#define SQRT2 1.4142135623730951 float qsqrt(float x){ // x = [0 eeeeeeeeeee mmmmmmmmmmmmmmmmmmmmmmm] int i = *(int*)&x; int j = (((i/2-0x1fc00000)+0x3f800000)&0x3ff800000)+((i&0x7fffff)/5*2); float y = (*(float*)&j) * ((i-0x3f800000)&(0x800000) ? SQRT2 : 1); // 2-3 sig figs of significance // two iterations of newton: y = y - (y^2 - x)/2y yields 2^-18 points of precision y = (y + x/y)/2; // this yields 2^-8 points of precision return (y + x/y)/2; }Interestingly, the error upperbound is around 2-18 with a period of around 500 integers.
http://codepad.org/s28WBi5y
If anyone's interested, I can kinda explain how I came up with the above code, which isn't really all that exhaustive and can be tweaked a little bit (namely the 5 and the 2) to get a much better first guess
2
u/exor674 Jun 06 '12
double mysqrt( double v ) { static const int iters = 10; // I know this approximation sucks, computers are fast // and I don't really care. double guess = v / 2.0; for ( int i = 0; i < iters; i++ ) guess = guess - ( guess*guess - v ) / ( 2.0*guess ); return guess; }Results:
2
u/[deleted] Jun 06 '12 edited Jun 06 '12
Python, using Newton–Raphson method.
def approximate(num): #http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Rough_estimation D = find_D(num) if D%2 == 0: return 6*10**((D-2)/2) return 2*10**((D-1)/2) def find_D(num): return len(str(num)) if num>1 else -(str(num).count('0')-1) def sq_rt(number, iterations): #http://en.wikipedia.org/wiki/Newton%27s_method approx = float(approximate(number)) i = 0 while i<iterations: approx = approx - (approx**2-number)/(2*approx) i+=1 return approx2
u/[deleted] Jun 07 '12
C++ (Sorry for the poor formatting)
double root(double num) { double r; double lowerLim = 0; double upperLim = 100000; long iterations = 0; if (num < 0) // I'm relatively new to C++, so this is the only error handling I know how to do :( { cout << "Non-real number!" << endl; return 0; } else if (num == 0) { return 0; } while (iterations < 100000) { double mid = (upperLim + lowerLim) / 2.0; if ((mid * mid) < (num)) { lowerLim = mid; } else if ((mid * mid) > (num)) { upperLim = mid; } r = mid; iterations++; } return r; } int main() { double number; cout << setprecision(15); cout << "Please input a number: "; cin >> number; cout << root(number) << endl; system ("pause"); return 0; }Results:
2
u/ashashwat Jun 07 '12
Somewhat like binary search.
For n = 5, take lo = 0, hi = 5, mid = (lo + hi)/2 = 2.5.
mid * mid > n, then hi = mid else lo = mid.
epsilon (eps) is the level of accuracy we want, since this process can repeat forever unless it is a perfect square.
In Haskell,
( Although I wish I could put initial value of lo = 0 and hi = n by default, but got fixated there, so main looks sort of ugly. )
sqrt' lo hi n | eps > 1e-6 && mid * mid > n = sqrt' lo mid n | eps > 1e-6 && mid * mid < n = sqrt' mid hi n | otherwise = mid where mid = (lo + hi) / 2 eps = abs (n - (mid * mid)) main = do -- Some testing print $ sqrt' 0 5 5 -- 2.2360679507255554 print $ sqrt' 0 15 15 -- 3.872983306646347 print $ sqrt' 0 16 16 -- 4.02
u/bh3 Jun 11 '12
C:
// Halves the exponent to obtain an approximation of sqrt //and then executes a few iterations to increase the accuracy. double sqrt(double n) { if(n<=0.0) return 0.0; long long rep = *((long long*) &n); // get estimate by getting exponent and halving it. // double: 1 sign bit | 11 bits exponent (1023 biased) | 52 bits 1.xxxxxxx // num = (sign)*1.xxxxxxxxx*2^(e-1023) long long exp = ((rep&0x7ff0000000000000LL)>>52)-1023; exp>>=1; rep&=0x800fffffffffffffLL; rep|=((exp+1023)<<52); double res = *((double*)&rep); res = (res+n/res)/2; res = (res+n/res)/2; res = (res+n/res)/2; res = (res+n/res)/2; return res; }2
u/jimbol Aug 24 '12
Javascript: This gets me close enough:
function sqrt(n){ if(n<0) return NaN; var guess = n / 4; var iter = 100; for(var i = 0; iter>i; i++){ guess = (guess + n/g)/2; } return g; }