|
Last change
on this file since 2058e5c was 2058e5c, checked in by istevanoska <ilinastevanoska@…>, 6 months ago |
|
Working / before login
|
-
Property mode
set to
100644
|
|
File size:
704 bytes
|
| Line | |
|---|
| 1 | /*
|
|---|
| 2 | Fraction.js v5.0.0 10/1/2024
|
|---|
| 3 | https://raw.org/article/rational-numbers-in-javascript/
|
|---|
| 4 |
|
|---|
| 5 | Copyright (c) 2024, Robert Eisele (https://raw.org/)
|
|---|
| 6 | Licensed under the MIT license.
|
|---|
| 7 | */
|
|---|
| 8 | const Fraction = require('fraction.js');
|
|---|
| 9 |
|
|---|
| 10 | // Calculates (a/b)^(c/d) if result is rational
|
|---|
| 11 | // Derivation: https://raw.org/book/analysis/rational-numbers/
|
|---|
| 12 | function root(a, b, c, d) {
|
|---|
| 13 |
|
|---|
| 14 | // Initial estimate
|
|---|
| 15 | let x = Fraction(100 * (Math.floor(Math.pow(a / b, c / d)) || 1), 100);
|
|---|
| 16 | const abc = Fraction(a, b).pow(c);
|
|---|
| 17 |
|
|---|
| 18 | for (let i = 0; i < 30; i++) {
|
|---|
| 19 | const n = abc.mul(x.pow(1 - d)).sub(x).div(d).add(x)
|
|---|
| 20 |
|
|---|
| 21 | if (x.n === n.n && x.d === n.d) {
|
|---|
| 22 | return n;
|
|---|
| 23 | }
|
|---|
| 24 | x = n;
|
|---|
| 25 | }
|
|---|
| 26 | return null;
|
|---|
| 27 | }
|
|---|
| 28 |
|
|---|
| 29 | root(18, 2, 1, 2); // 3/1
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.