How to use the mathjs.parse function in mathjs

To help you get started, we’ve selected a few mathjs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github josdejong / mathjs / examples / algebra.js View on Github external
// expressions in an expression tree and do algebraic operations like
// simplification and derivation on this tree.

// load math.js (using node.js)
const math = require('mathjs')

// simplify an expression
console.log('simplify expressions')
console.log(math.simplify('3 + 2 / 4').toString()) // '7 / 2'
console.log(math.simplify('2x + 3x').toString()) // '5 * x'
console.log(math.simplify('2 * 3 * x', { x: 4 }).toString()) // '24'
console.log(math.simplify('x^2 + x + 3 + x^2').toString()) // '2 * x ^ 2 + x + 3'
console.log(math.simplify('x * y * -x / (x ^ 2)').toString()) // '-y'

// work with an expression tree, evaluate results
const f = math.parse('2x + x')
const simplified = math.simplify(f)
console.log(simplified.toString()) // '3 * x'
console.log(simplified.eval({ x: 4 })) // 12
console.log()

// calculate a derivative
console.log('calculate derivatives')
console.log(math.derivative('2x^2 + 3x + 4', 'x').toString()) // '4 * x + 3'
console.log(math.derivative('sin(2x)', 'x').toString()) // '2 * cos(2 * x)'

// work with an expression tree, evaluate results
const h = math.parse('x^2 + x')
const dh = math.derivative(h, 'x')
console.log(dh.toString()) // '2 * x + 1'
console.log(dh.eval({ x: 3 })) // '7'
github vcync / modV / src / extra / expression / store.js View on Github external
function compileExpression(expression, additionalScope = {}) {
  const scope = { value: 0, delta: 0, map: window.Math.map }

  Object.keys(additionalScope).forEach(key => {
    scope[key] = additionalScope[key]
  })

  // provide a scope
  let newFunction
  try {
    const node = math.parse(expression, scope)

    newFunction = node.compile()
    newFunction.eval(scope)
  } catch (e) {
    return false
  }

  return newFunction
}
github arxitics / arxiv-analytics / routes / tools.js View on Github external
tools.post('/parser', function (req, res) {
  var body = req.body;
  var expr = String(body.expr).replace(/\;?\s*\r?\n\s*/g, '; ').trim();
  var data = {expr: expr};
  try {
    var node = math.parse(expr);
    var tex = node.toTex();
    if (tex !== node.toString() && /\\\w/.test(tex)) {
      data.tex = /\\(frac|begin)/.test(tex) ? '$$' + tex + '$$' : '$' + tex + '$';
    }
    data.result = math.eval(expr);
  } catch (error) {
    data.error = error.message;
  }
  res.json(data);
});
github kisonecat / math-expressions / spec / quick_mathjs-to-ast.spec.js View on Github external
test("parses " + string, () => {
        expect(flatten(converter.convert(math.parse(string)))).toEqual(trees[string]);
    });
  });
github ealgis / ealgis / frontend / src / redux / modules / databrowser.tsx View on Github external
export function parseColumnsFromValueExpression(
    expression: string,
    expression_mode: eLayerValueExpressionMode,
    expression_side_to_parse: string = "both"
) {
    const parsed: any = parse(expression)
    let node
    if (expression_side_to_parse === "left") {
        node = parsed.args[0].content.args[0]
    } else if (expression_side_to_parse === "right") {
        node = parsed.args[0].content.args[1]
    } else if (expression_side_to_parse === "both") {
        node = parsed
    }
    return node.filter((node: any) => node.isAccessorNode).map((node: any) => node.toString())
}
github ealgis / ealgis / frontend / src / redux / modules / databrowser.tsx View on Github external
export function parseColumnsFromExpression(expression: string, expression_mode: eLayerValueExpressionMode | eLayerFilterExpressionMode) {
    const parsed: any = parse(expression)
    return parsed.filter((node: any) => node.isAccessorNode).map((node: any) => node.toString())
}
github apache / incubator-superset / superset / assets / src / explore / components / controls / AnnotationLayer.jsx View on Github external
isValidFormula(value, annotationType) {
    if (annotationType === ANNOTATION_TYPES.FORMULA) {
      try {
        mathjs
          .parse(value)
          .compile()
          .eval({ x: 0 });
      } catch (err) {
        return true;
      }
    }
    return false;
  }
github GeoTIFF / geoblaze / src / band-arithmetic / band-arithmetic.module.js View on Github external
return new Promise((resolve, reject) => {
    if (georaster.values.length < 2) {
      return reject(new Error('Band arithmetic is not available for this raster. Please make sure you are using a multi-band raster.'));
    }

    const parseError = arithmeticError(arithmetic);
    if (parseError) return reject(new Error(parseError));

    try {
      const bands = georaster.values;
      const noDataValue = georaster.noDataValue;
      const values = [];
      const numRows = bands[0].length;

      const ast = parse(arithmetic.toLowerCase());
      const arithmeticFunction = parseAST(ast, bands.length);

      for (let i = 0; i < numRows; i++) {
        const bandRows = getBandRows(bands, i);
        const row = [];
        const numValues = bandRows[0].length;

        for (let j = 0; j < numValues; j++) {
          const bandValues = getBandValues(bandRows, j);
          if (containsNoDataValue(bandValues, noDataValue)) {
            row.push(noDataValue);
          } else {
            const value = arithmeticFunction(...bandValues);
            if (value === Infinity || value === -Infinity || isNaN(value)) {
              row.push(noDataValue);
            } else {
github chrisdruta / arithmusic / src / components / App.tsx View on Github external
const GenerateTex = (expression: string) => {
  const parsedMath = math.simplify(math.parse(expression));
  return `\\LARGE f(x)=${parsedMath.toTex()}`;
}

mathjs

Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser with support for symbolic computation, comes with a large set of built-in functions and constants, and offers an integrated solution to work with dif

Apache-2.0
Latest version published 8 days ago

Package Health Score

92 / 100
Full package analysis