rational-pow.js 704 B

1234567891011121314151617181920212223242526272829
  1. /*
  2. Fraction.js v5.0.0 10/1/2024
  3. https://raw.org/article/rational-numbers-in-javascript/
  4. Copyright (c) 2024, Robert Eisele (https://raw.org/)
  5. Licensed under the MIT license.
  6. */
  7. const Fraction = require('fraction.js');
  8. // Calculates (a/b)^(c/d) if result is rational
  9. // Derivation: https://raw.org/book/analysis/rational-numbers/
  10. function root(a, b, c, d) {
  11. // Initial estimate
  12. let x = Fraction(100 * (Math.floor(Math.pow(a / b, c / d)) || 1), 100);
  13. const abc = Fraction(a, b).pow(c);
  14. for (let i = 0; i < 30; i++) {
  15. const n = abc.mul(x.pow(1 - d)).sub(x).div(d).add(x)
  16. if (x.n === n.n && x.d === n.d) {
  17. return n;
  18. }
  19. x = n;
  20. }
  21. return null;
  22. }
  23. root(18, 2, 1, 2); // 3/1