source: node_modules/fraction.js/examples/integrate.js@ 505f39a

Last change on this file since 505f39a was 2058e5c, checked in by istevanoska <ilinastevanoska@…>, 6 months ago

Working / before login

  • Property mode set to 100644
File size: 1.8 KB
Line 
1/*
2Fraction.js v5.0.0 10/1/2024
3https://raw.org/article/rational-numbers-in-javascript/
4
5Copyright (c) 2024, Robert Eisele (https://raw.org/)
6Licensed under the MIT license.
7*/
8const Fraction = require('fraction.js');
9
10// NOTE: This is a nice example, but a stable version of this is served with Polynomial.js:
11// https://github.com/rawify/Polynomial.js
12
13function integrate(poly) {
14
15 poly = poly.replace(/\s+/g, "");
16
17 var regex = /(\([+-]?[0-9/]+\)|[+-]?[0-9/]+)x(?:\^(\([+-]?[0-9/]+\)|[+-]?[0-9]+))?/g;
18 var arr;
19 var res = {};
20 while (null !== (arr = regex.exec(poly))) {
21
22 var a = (arr[1] || "1").replace("(", "").replace(")", "").split("/");
23 var b = (arr[2] || "1").replace("(", "").replace(")", "").split("/");
24
25 var exp = new Fraction(b).add(1);
26 var key = "" + exp;
27
28 if (res[key] !== undefined) {
29 res[key] = { x: new Fraction(a).div(exp).add(res[key].x), e: exp };
30 } else {
31 res[key] = { x: new Fraction(a).div(exp), e: exp };
32 }
33 }
34
35 var str = "";
36 var c = 0;
37 for (var i in res) {
38 if (res[i].x.s !== -1n && c > 0) {
39 str += "+";
40 } else if (res[i].x.s === -1n) {
41 str += "-";
42 }
43 if (res[i].x.n !== res[i].x.d) {
44 if (res[i].x.d !== 1n) {
45 str += res[i].x.n + "/" + res[i].x.d;
46 } else {
47 str += res[i].x.n;
48 }
49 }
50 str += "x";
51 if (res[i].e.n !== res[i].e.d) {
52 str += "^";
53 if (res[i].e.d !== 1n) {
54 str += "(" + res[i].e.n + "/" + res[i].e.d + ")";
55 } else {
56 str += res[i].e.n;
57 }
58 }
59 c++;
60 }
61 return str;
62}
63
64var poly = "-2/3x^3-2x^2+3x+8x^3-1/3x^(4/8)";
65
66console.log("f(x): " + poly);
67console.log("F(x): " + integrate(poly));
Note: See TracBrowser for help on using the repository browser.