1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| /*
| * newton-method-sqrt.js
| *
| */
|
| import {terminal} from "./dfhi.js";
|
| window.main = function(...argv) {
| let testData = [0, 1.25, 3.758, 4.229, 6.735, 123456.789, (1<<30) + 1];
| for(let c of testData) {
| let cquad = c*c;
| let csqrt = sqrt(cquad);
| let msqrt = Math.sqrt(cquad);
| terminal.printl({"quadrat": cquad, "sqrt":csqrt, "Math.sqrt":msqrt, "expected": c})
| }
| };
|
| function sqrt(c) {
| const EPSILON = 1E-16;
| let xn = c;
| let q = c/xn; // auxiliary variable to avoid multiple division c/xn
| // !\left| \frac{x^2 - c}{c} \right| > \varepsilon!
| while(Math.abs(xn - q) > EPSILON*q ) { // same as |xn - c/xn| > EPSILON * c/xn
| xn = (q + xn) / 2;
| q = c/xn;
| }
| return xn;
| }
|
|