1
\$\begingroup\$

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.

\$\endgroup\$
4
  • 2
    \$\begingroup\$ 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? \$\endgroup\$ – FromTheStackAndBack May 11 at 21:36
  • 4
    \$\begingroup\$ What hardware is this running on? I have heard seems like dangerous justification to make a design decision like this. \$\endgroup\$ – Reinderien May 11 at 23:28
  • \$\begingroup\$ Steve, "based on my observations four iterations give good results" --> Try DBL_MAX, DBL_MIN \$\endgroup\$ – chux - Reinstate Monica May 13 at 20:02
  • \$\begingroup\$ What are you looking for from a code review, it remains unclear to me. \$\endgroup\$ – pacmaninbw Jul 2 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.