# Find the square root, BUT [closed]

Write a square root function that takes an input, positive or negative, and calculate it's square root, correct up to six decimal places (then truncate after the sixth decimal place). But, you cannot use ANY built in power related functions. This means nothing like (but not limited to):

Math.pow(n,0.5)
sqrt(2)
root(n,2)
n**0.5
etc.


This means that you're going to have to use (or create) a method to find the square root. Two common methods are the Babylonian/bisector method and Newton's method, but feel free to create your own!

Output can be either printed to the console or returned. Your choice.

Examples:

Input:
sqrt(4) //you can call your function whatever you want
Output:
2
Input:
7
Output:
2.645751
Input:
5.0625
Output:
2.25
Input:
-15
Output:
3.872983i
Input:
-9
Output:
3i


This is code golf, so shortest code in bytes wins!

Remember, no built ins that have anything to do with powers!

If you have any questions, please, tell me in the comments and I'll clarify promptly.

• Is e^x allowed? (I'm guessing not) – a spaghetto Feb 8 '16 at 22:29
• Also, 6 decimal places is somewhat ambiguous, do you mean six significant figures? Otherwise this becomes dramatically more complicated given a 50 digit input. – FryAmTheEggman Feb 8 '16 at 22:42
• "Do X without Y" challenges are generally a bad idea, and this one hits the usual pitfalls. – xnor Feb 8 '16 at 23:01
• Try, for example 500000000000000000 as input, the output should be 707106781.18654752 ish, is the result then 707106000? Can it be in scientific notation? These general floating point issues make a good case for using the sandbox. – FryAmTheEggman Feb 8 '16 at 23:15
• I voted to close this as unclear and the other one as a dupe. The old challenge was broken (all of the answers were just **.5), whereas this has a better chance of being a good challenge. I am concerned, like @xnor, about the viability of a challenge of this type, however. – lirtosiast Feb 8 '16 at 23:58

# c (function), 166

Now with complex numbers. Uses the GCC complex number extension.

Straightforward golfing of the famous Fast inverse square root method. This method gives 1/sqrt(n), so we simply multiply this by n to give sqrt(n):

#include <complex.h>
#define M y*=1.5-n*y*y/2
i;_Complex float f(float m){float y,n;n=m>0?m:-m;y=n;i=0x5f3759df-*(int*)&y/2;y=*(float*)&i;M;M;M;return m>0?y*n:y*n*I;}


The famous snippet of Quake code only does one iteration of Newton's method, which gives a fairly inaccurate answer. Three iterations here seems to be enough for 6 decimal places, at least for the testcases.

Try it online.

• Isn't this not-your-IP and should thus be CW? Or could you at least link to the source file (there are github repos of Quake source)? – cat Apr 14 '16 at 0:24
• @cat OK - CWed and github URL added. – Digital Trauma Apr 14 '16 at 5:26