0

Im trying to do a function where I enter two different algebraic expressions and have a variable list to change them into numbers. However, it do not recognise the variables if they do not have an operator in between them like in this case:

let exp1 = 'x*y'
let exp2 = 'xy'
const variableList = {
x: 1.00
y: 1.50
}
mathjs.evaluate(exp1, variableList) // 1.5
mathjs.evaluate(exp2, variableList) // Error
return mathjs.equal(exp1, exp2)

Is there anyway to make it understand two variables in a row without an operator? It should also be possible to write units so for example I do not want "cups" to become "c* u * p * s" if possible.

  • You can write another function to convert `cups` in to `c* u * p * s` so you can call it like `mathjs.evaluate(exp2, expand(variableList))` but i don't think it gives you any advantage – Madhawa Priyashantha Dec 14 '21 at 10:35
  • So I do not want to convert cups into c* u* p* s but I do want xy to become x* y. Or interpret as x*y – Hamberg Dec 14 '21 at 10:39
  • 1
    You need to create logic that defines if and when `cu` should be converted to `c*u` (variable names are single character) versus when it does not (variable names are multi character). – Peter B Dec 14 '21 at 10:45

1 Answers1

0

Not sure if this would work for you but you can import your own helper function for evaluating expressions such as "xy":

math.import({
  xy: function(exp, scope) {
    exp = exp.split('').join('*')
    return math.evaluate(exp, scope)
  }
})

let exp1 = 'x*y'
let exp2 = 'xy'

const variableList = {
  x: 1.00,
  y: 1.50
}

let result1 = math.evaluate(exp1, variableList)
let result2 = math.xy(exp2, variableList)

console.log(result1) // 1.5
console.log(result2) // 1.5
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/10.0.0/math.js"></script>
Timur
  • 1,682
  • 1
  • 4
  • 11