Debian Codegraph @

fractionjs/examples/approx.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 // Another rational approximation, not using Farey Sequences but Binary Search using the mediant
10 function approximate(p, precision) {
11
12 var num1 = Math.floor(p);
13 var den1 = 1;
14
15 var num2 = num1 + 1;
16 var den2 = 1;
17
18 if (p !== num1) {
19
20 while (den1 <= precision && den2 <= precision) {
21
22 var m = (num1 + num2) / (den1 + den2);
23
24 if (p === m) {
25
26 if (den1 + den2 <= precision) {
27 den1 += den2;
28 num1 += num2;
29 den2 = precision + 1;
30 } else if (den1 > den2) {
31 den2 = precision + 1;
32 } else {
33 den1 = precision + 1;
34 }
35 break;
36
37 } else if (p < m) {
38 num2 += num1;
39 den2 += den1;
40 } else {
41 num1 += num2;
42 den1 += den2;
43 }
44 }
45 }
46
47 if (den1 > precision) {
48 den1 = den2;
49 num1 = num2;
50 }
51 return new Fraction(num1, den1);
52 }
53