Checking Math Input for Correct Rational Expression

The more complicated (but stable) method is to evaluate a function AND check that certain numbers were used (since you’re looking for a particular format), so for your example above:

#student expression
exp=this.latex
#student input as a function
f=simpleFunction(exp)
check= f.evaluateAt(3)=0 and f.evaluateAt(2)=-0.2
    and countNumberUsage(exp,3)=1 and countNumberUsage(exp,2)=1
    and countNumberUsage(exp,1)=1

You want to evaluate at as many values you feel is adequate. I only did a few but you can add more. countNumberUsage counts the occurrence of a particular number (not digit) in an expression. It does not take negatives. So, both -2x and 2x would count one 2, but evaluating the expression takes care of ambiguity.

You do need to consider if you want to accept a student writing “1x”, so you may want:

... and (countNumberUsage(exp,1)=1 or countNumberUsage(exp,1)=2)
2 Likes