|
Last change
on this file was 2058e5c, checked in by istevanoska <ilinastevanoska@…>, 6 months ago |
|
Working / before login
|
-
Property mode
set to
100644
|
|
File size:
1.1 KB
|
| 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 | // Another rational approximation, not using Farey Sequences but Binary Search using the mediant
|
|---|
| 11 | function approximate(p, precision) {
|
|---|
| 12 |
|
|---|
| 13 | var num1 = Math.floor(p);
|
|---|
| 14 | var den1 = 1;
|
|---|
| 15 |
|
|---|
| 16 | var num2 = num1 + 1;
|
|---|
| 17 | var den2 = 1;
|
|---|
| 18 |
|
|---|
| 19 | if (p !== num1) {
|
|---|
| 20 |
|
|---|
| 21 | while (den1 <= precision && den2 <= precision) {
|
|---|
| 22 |
|
|---|
| 23 | var m = (num1 + num2) / (den1 + den2);
|
|---|
| 24 |
|
|---|
| 25 | if (p === m) {
|
|---|
| 26 |
|
|---|
| 27 | if (den1 + den2 <= precision) {
|
|---|
| 28 | den1 += den2;
|
|---|
| 29 | num1 += num2;
|
|---|
| 30 | den2 = precision + 1;
|
|---|
| 31 | } else if (den1 > den2) {
|
|---|
| 32 | den2 = precision + 1;
|
|---|
| 33 | } else {
|
|---|
| 34 | den1 = precision + 1;
|
|---|
| 35 | }
|
|---|
| 36 | break;
|
|---|
| 37 |
|
|---|
| 38 | } else if (p < m) {
|
|---|
| 39 | num2 += num1;
|
|---|
| 40 | den2 += den1;
|
|---|
| 41 | } else {
|
|---|
| 42 | num1 += num2;
|
|---|
| 43 | den1 += den2;
|
|---|
| 44 | }
|
|---|
| 45 | }
|
|---|
| 46 | }
|
|---|
| 47 |
|
|---|
| 48 | if (den1 > precision) {
|
|---|
| 49 | den1 = den2;
|
|---|
| 50 | num1 = num2;
|
|---|
| 51 | }
|
|---|
| 52 | return new Fraction(num1, den1);
|
|---|
| 53 | }
|
|---|
| 54 |
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.