Debian Codegraph @

fractionjs/examples/rational-pow.js

raw symbols SCIP
1 /**
2 * @license Fraction.js v2.7.0 01/06/2015
3 * http://www.xarg.org/2014/03/rational-numbers-in-javascript/
4 *
5 * Copyright (c) 2015, Robert Eisele ([email protected])
6 * Dual licensed under the MIT or GPL Version 2 licenses.
7 **/
8
9 // Calculates (a/b)^(c/d) if result is rational
10 function root(a, b, c, d) {
11
12 // Initial estimate
13 var xn = Fraction(Math.floor(Math.pow(a / b, c / d)));
14 var abc = Fraction(a, b).pow(c);
15
16 for (var i = 0; i < 30; i++) {
17 var xp = xn.sub(xn.pow(d).sub(abc).div(xn.pow(d - 1).mul(d)));
18
19 if (xp.n === xn.n && xp.d === xn.d) {
20 return xp;
21 }
22 xn = xp;
23 }
24 return null;
25 }
26
27 root(18, 2, 1, 2); // 3/1
28
29 /* derivation:
30
31 Root: x = (a/b)^(c/d)
32 <=> x^d = (a/b)^c
33 <=> x^d - (a/b)^c = 0
34
35 f(x) = x^d - (a/b)^c
36 f'(x) = dx^(d-1)
37
38 Newton method:
39 xp = xn - f(xn) / f'(xn)
40
41 */