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
Asked
Active
Viewed 328 times
-6
-
What is the question what is the code? Math.sqrt(Math.pow(n,11)); – Ullas Hunka Jul 18 '18 at 10:20
-
2Its your HOMEWORK so at-least try something and its already there [`Math.sqrt()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt). – Satpal Jul 18 '18 at 10:22
-
image with task not loaded – Mykhailo Dulyba Jul 18 '18 at 10:28
2 Answers
0
Looks like your requirement is not just finding the square root of a number. If by any chance that is your requirement, use Math.sqrt.
If your requirement is to implement a function to find the square root for educational purpose, what you need is to write a recursive function as below. Modify the code as required to support error at 10^-6
function sqrt(A, i = 0) {
if (i === 0)
return A;
let prev = sqrt(A, i - 1);
return 0.5 * (prev + (A / prev));
}
console.log(sqrt(2,1000));
console.log(sqrt(3,1000));
console.log(sqrt(9,1000));
console.log(sqrt(25,1000));

Chathura Widanage
- 653
- 5
- 14
0
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));

Nina Scholz
- 376,160
- 25
- 347
- 392