integrate.js 1.8 KB

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