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

2

5

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
Causal answered 23/9, 2018 at 17:18 Comment(1)
Math.sqrt isn't a "library method", it's built-in...Uralite
R
13

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
Ransdell answered 23/9, 2018 at 17:27 Comment(4)
thank U for help! Can U explain why did U use DO...WHILE but not WHILE?Cairn
because you need first a new value and then the check.Ransdell
This function causes a timeout error when a is zero 0. Use if (a === 0) return a;.Electrochemistry
@csr-nontol, you can edit the answer, if you like.Ransdell
T
2

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);
}
Thompson answered 23/9, 2018 at 18:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.