jiggzson / nerdamer

a symbolic math expression evaluator for javascript
http://www.nerdamer.com
MIT License
514 stars 82 forks source link

Invalid equations with number variables #585

Closed sametaylak closed 3 years ago

sametaylak commented 3 years ago
const equation = "foo__16_bar=foo__16 - bar__16"
const variableToSolve = "foo__16"
const factoredEquation = nerdamer(equation).solveFor(variableToSolve).toString()

console.log(factoredEquation) \\ => (-_bar+1)^(-1)*bar__16

I am trying to solve an equation with above example but It is creating invalid variable.

_bar should be foo__16_bar - I think It is respecting after the number part

jiggzson commented 3 years ago

@sametaylak, noted. That's an interesting bug. I'll look into it. Thanks for reporting.

jiggzson commented 3 years ago
const equation = nerdamer("foo__16_bar");
console.log(equation.toString()); //"_bar*foo__16"

Which is clearly wrong. The issue seems to be implicit multiplication. Cases such as 4_x wouldn't work anymore by treating foo__16_bar as one variable. The only solution I can think of add a setting for cases such as these. Thoughts?

jiggzson commented 3 years ago

@sametaylak, I forgot to @mention you.

jiggzson commented 3 years ago

@sametaylak, I don't normally recommend regex solutions but in this particular case I personally think it makes sense. I've moved the regex which is used to detect variables in the Settings object. Normally the regex looks like this /([\+\-\/\*]*[0-9]+)([a-z_αAβBγΓδΔϵEζZηHθΘιIκKλΛμMνNξΞoOπΠρPσΣτTυϒϕΦχXψΨωΩ]+[\+\-\/\*]*)/gi. In your case, you don't want variables to start with an underscore so we can remove it from the regex and overwrite the one that nerdamer uses. So you end up with something like this

nerdamer.set('IMPLIED_MULTIPLICATION_REGEX', /([\+\-\/\*]*[0-9]+)([a-zαAβBγΓδΔϵEζZηHθΘιIκKλΛμMνNξΞoOπΠρPσΣτTυϒϕΦχXψΨωΩ]+[\+\-\/\*]*)/gi)
const equation = nerdamer("foo__16_bar*foo__16_bar");
console.log(equation.toString()); //"foo__16_bar^2"

The underscore is ignored and treated as part of the variable. This is currently on the dev branch but will be part of version 1.1.8.