Making a square root function

I understand that you can use std::sqrt.

I would like to avoid using cmath library and make my own function to do this.I have tried doing things like x^0.5 but when running it this does not work.

I have even looked at an old Babylonian method:https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
however this has some error.

any ideas?

however this has some error

What's wrong with it? It's just Newton-Raphson applied to x2-A =0.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <cmath>               // or write your own abs() function
using namespace std;

double mySqrt( double A )
{
   double epsilon = 1.0e-30;      // for example
   if ( A < epsilon ) return 0.0;

   double x = 1.0, xold = 2.0;

   while ( abs( x - xold ) > epsilon )
   {
      xold = x;
      x = 0.5 * ( x + A / x );     // main iteration
   }
   return x;
}


int main()
{
   double tests[] = { 1.0e-20, 0.0001, 0.0144, 1.0, 1.44, 10000.0, 1.0e20 };
   for ( double A : tests ) cout << A << '\t' << mySqrt( A ) << '\n';
}


1e-20	1e-10
0.0001	0.01
0.0144	0.12
1	1
1.44	1.2
10000	100
1e+20	1e+10
Last edited on
do not do this apart from as a learning exercise. The CPUs, at least CISC cpu, have this in hardware and are orders of magnitude faster than you can do it even if you do it with an optimal algorithm (and this thing is far from optimal).

There are only 2 functions in cmath that I am aware of as being suboptimal:
integer powers (whether the base is integer or double is irrelevant) and abs (which should be little more than a bit operation, but theirs is, or was a few years back, slowish compared to just doing the logic directly via a macro). If you find something else worth doing (again, apart from doing it for fun) by hand, I would be interested to know about it.

pow(x, 0.5) works just fine.
remember that ^ is xor …!

if your sqrts are bounded (not generic, but say zero to 10 or so) you can make a lookup table and interpolate in a couple of iterations, and either use that approximation directly or use it as a feed forward into the iteration, with a better starting point so it converges faster (fewer loops).


Are you looking for speed? What is your goal here?
Last edited on
I was trying to get the most efficient and most accurate way to find the square root but now I see this might be foolish.
unless you are on a CPU that does not directly support it, you will not succeed in code.

Its really, really tough to beat a dedicated circuit with code :)
And yes, Ive tried some of this too. I once, in the early 90s, spent a couple of days trying to cook up a faster sin function and learned this same lesson.
Topic archived. No new replies allowed.