Debian Codegraph @

fractionjs/examples/integrate.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 // NOTE: This is a nice example, but a stable version of this is served with Polynomial.js:
10 // https://github.com/infusion/Polynomial.js
11
12 var Fraction = require('../fraction.min.js');
13
14 function integrate(poly) {
15
16 poly = poly.replace(/\s+/g, "");
17
18 var regex = /(\([+-]?[0-9/]+\)|[+-]?[0-9/]+)x(?:\^(\([+-]?[0-9/]+\)|[+-]?[0-9]+))?/g;
19 var arr;
20 var res = {};
21 while (null !== (arr = regex.exec(poly))) {
22
23 var a = (arr[1] || "1").replace("(", "").replace(")", "").split("/");
24 var b = (arr[2] || "1").replace("(", "").replace(")", "").split("/");
25
26 var exp = new Fraction(b).add(1);
27 var key = "" + exp;
28
29 if (res[key] !== undefined) {
30 res[key] = {x: new Fraction(a).div(exp).add(res[key].x), e: exp};
31 } else {
32 res[key] = {x: new Fraction(a).div(exp), e: exp};
33 }
34 }
35
36 var str = "";
37 var c = 0;
38 for (var i in res) {
39 if (res[i].x.s !== -1 && c > 0) {
40 str += ("+");
41 } else if (res[i].x.s === -1) {
42 str += ("-");
43 }
44 if (res[i].x.n / res[i].x.d !== 1) {
45 if (res[i].x.d !== 1) {
46 str += ("" + res[i].x.n + "/" + res[i].x.d + "");
47 } else {
48 str += ("" + res[i].x.n);
49 }
50 }
51 str += ("x");
52 if (res[i].e.n / res[i].e.d !== 1) {
53 str += ("^");
54 if (res[i].e.d !== 1) {
55 str += ("(" + res[i].e.n + "/" + res[i].e.d + ")");
56 } else {
57 str += ("" + res[i].e.n);
58 }
59 }
60 c++;
61 }
62 return str;
63 }
64
65 var poly = "-2/3x^3-2x^2+3x+8x^3-1/3x^(4/8)";
66
67 console.log("f(x): " + poly);
68 console.log("F(x): " + integrate(poly));