# Implementation of the square root for real time application

For the real time control software I need square root calculation. I have heard that the sqrt function from the standard library isn't good choice due to the unpredictable number of iterations used during calculation. Based on that information I have decided to implement the sqrt function in my own based on the Newton tangent method. So I have exploited the iteration formula

$$x_{k+1} = -\frac{f(x_k)}{f'(x_k)} + x_k,$$ where $$f(x) = x^2 - a$$ and $$a\in\mathbb R_0^+, a_{min} = 0.1, a_{max} = 400.0$$.

Based on the above mentioned formulas I have

$$x_{k+1} = \frac{1}{2}\cdot\left(x_k + \frac{a}{x_k}\right)$$

I have chosen $$x(0) = 2$$ and based on my observations four iterations give good results in comparison with the sqrt from the standard library.

#define ITERATIONS 4

double squareRoot(double a)
{
double xk  = 2.0; // x(k)

uint8_t k;
for(k = 0; k < ITERATIONS; k++)
{
xk  = 0.5*(xk + a/xk);
}

return xk;
}


Despite that fact I have some doubts regarding the choice of the initial value and number of iterations.

• For what values of a do you expect to get? Negatives? Small positives? Integers? What is min and max value? What is the error threshold? – FromTheStackAndBack May 11 at 21:36
• What hardware is this running on? I have heard seems like dangerous justification to make a design decision like this. – Reinderien May 11 at 23:28
• Steve, "based on my observations four iterations give good results" --> Try DBL_MAX, DBL_MIN – chux - Reinstate Monica May 13 at 20:02
• What are you looking for from a code review, it remains unclear to me. – pacmaninbw Jul 2 at 12:32