|
9 | 9 |
|
10 | 10 | export const agm = (a, g) => {
|
11 | 11 | if (a === g) return a; //avoid rounding errors, and increase efficiency
|
12 | | - let x; //temp var, for detecting rounding differences between `sqrt` and division |
| 12 | + let x; //temp var |
13 | 13 | do {
|
14 | 14 | [a, g, x] = [(a + g) / 2, Math.sqrt(a * g), a]
|
15 | 15 | } while (a !== x && !isNaN(a));
|
16 | 16 | /*
|
17 | 17 | `x !== a` ensures the return value has full precision,
|
18 | | - and prevents infinite loops caused by rounding errors (no need for "epsilon"). |
| 18 | + and prevents infinite loops caused by rounding differences between `div` and `sqrt` (no need for "epsilon"). |
| 19 | + If we were to compare `a` with `g`, some input combinations (not all) can cause an infinite loop, |
| 20 | + because the rounding mode never changes at runtime. |
19 | 21 | Precision is not the same as accuracy, but they're related.
|
20 | 22 | This function isn't always 100% accurate (round-errors), but at least is more than 95% accurate.
|
21 | | - `!isNaN(x)` prevents infinite loops caused by invalid inputs like: negatives, NaNs and both Infinities. |
| 23 | + `!isNaN(x)` prevents infinite loops caused by invalid inputs like: negatives, NaNs and Infinities. |
22 | 24 | */
|
23 | | -return a |
| 25 | +return a; |
24 | 26 | }
|
0 commit comments