|
| 1 | +/** |
| 2 | + * lazy-linked-lists |
| 3 | + * Lazy and infinite linked lists for JavaScript. |
| 4 | + * |
| 5 | + * example.js |
| 6 | + * |
| 7 | + * Examples of usage for lazy-linked-lists. |
| 8 | + * @license ISC |
| 9 | + */ |
| 10 | + |
| 11 | +import * as lazy from '../source'; |
| 12 | + |
| 13 | +/** |
| 14 | + * Compute the square root of a number using the Newton-Raphson method. |
| 15 | + * Adapted from "Why Functional Programming Matters" by John Hughes. |
| 16 | + * @param {number} a0 - initial estimate |
| 17 | + * @param {number} eps - tolerance |
| 18 | + * @param {number} n - number |
| 19 | + * @returns {number} The square root of `n` |
| 20 | + * @kind function |
| 21 | + * @example |
| 22 | + * sqrt(1,0,2); // => 1.414213562373095 |
| 23 | + * sqrt(1,0,144); // => 12 |
| 24 | + * relativeSqrt(1,0,144); // optimized version for very small and very large numbers |
| 25 | + */ |
| 26 | +const sqrt = (a01, eps0, n) => within(eps, lazy.iterate(next.bind(null, n), a0)); |
| 27 | + |
| 28 | +const relativeSqrt = (a0, eps, n) => relative(eps, lazy.iterate(next.bind(null, n), a0)); |
| 29 | + |
| 30 | +const next = (n, x) => (x + n/x) / 2; |
| 31 | + |
| 32 | +const within = (eps, rest) => { |
| 33 | + let a = lazy.index(rest, 0), b = lazy.index(rest, 1); |
| 34 | + return Math.abs(a - b) <= eps ? b : within(eps, lazy.drop(1, rest)); |
| 35 | +} |
| 36 | + |
| 37 | +const relative = (eps, rest) => { |
| 38 | + let a = lazy.index(rest, 0), b = lazy.index(rest, 1); |
| 39 | + return Math.abs(a - b) <= eps * Math.abs(b) ? b : relative(eps, lazy.drop(1, rest)); |
| 40 | +} |
0 commit comments