Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the square root without using library and built-in methods in Javascript?

Please help me to write a function to compute the square root of positive real numbers using the formula:

x i+1 = (1/2) * (xi + (A / x1)),

where 'A' - input real number.

On the zero iteration next statements have been taken x0 = A The error should be at least 10-6

Output

sqrt (2) = 1.414
sqrt (9) = 3
sqrt (25) = 5
like image 765
Елисей Горьков Avatar asked Sep 23 '18 17:09

Елисей Горьков


2 Answers

You could take xi (x) and the new value of xi + 1 (x1) and check if the values are equal. Then end the series and return that value.

For starting, you need an apporopriate value like the half of the given value.

function sqrt(a) {
    var x,
        x1 = a / 2;
        
    do {
        x = x1;
        x1 = (x + (a / x)) / 2;
    } while (x !== x1);
    return x;
}

console.log(sqrt (2)); // 1.414
console.log(sqrt (9)); // 3
console.log(sqrt (25)); // 5
like image 75
Nina Scholz Avatar answered Oct 21 '22 12:10

Nina Scholz


You can also use bisection - a more general method for solving problems:

var sqrt = function(n) {
    if (n<0) {
        throw "are you kidding?! we are REAL here.";
    }
    if (n === 0) {
        return 0;
    }
    var bisect = function(l,r) {
        var avg = (l+r)/2;
        if (r-l<0.00000001) {
            return (l+r)/2;
        }
        if (avg*avg > n) {
            return bisect(l, avg);
        } else if (avg*avg < n) {
            return bisect(avg, r);
        }
    }
    return bisect(0, n < 1 ? 1 : n);
}
like image 42
agsigma Avatar answered Oct 21 '22 10:10

agsigma