Search code examples
javascriptsqrt

How find square root n by computing the next Xi term on javascript


Write the function sqrt(A) for computing square root of positive real numbers using next numerical method xi+1 = (1/2) * (xi +(A/xi)). Where the A - input rial number; On zero iteration next statements have been taken: x0 = A; The error should be at least 10^-6


Solution

  • You could take the last value xi-1 and compare it with the new value xi instead of using a loop counter.

    function sqrt(a, x = 1) {    // take 1 for x(0) as start value for recursion
        var y = (x + a / x) / 2; // prepare next value x(i+1)
    
        if (x === y) {           // exit condition
            return x;
        }
        return sqrt(a, y);       // tail call optimization 
    }                            // https://stackoverflow.com/q/310974/1447675
    
    console.log(sqrt(2));
    console.log(sqrt(10));
    console.log(sqrt(9));
    console.log(sqrt(25));