WeBWorK Problems

Testing for simplified form (division by zero)

Testing for simplified form (division by zero)

by D. Brian Walton -
Number of replies: 2
For problems looking at the definition of the derivative, there is the step [f(x+h)-f(x)]/h where one typically needs to do some algebraic simplification (when possible) to find a form that is continuous at h=0 in preparation for taking the limit.

I would like to use AnswerHints so that if they type in the correct form for [f(x+h)-f(x)]/h but have not yet simplified that it gives a suggestion to first simplify their answer.

I have tried to evaluate the students answer with h=0, but do not know how to avoid the PERL error of division by zero.  I tried to use "eval" (see below), but this gives me another error:

'eval "string"' trapped by operation mask at line 94

What strategies might anyone who has done something similar recommend?

- Brian Walton

============== Code snippet =============

$expr = Compute("sqrt(x+$a)")->reduce('(-x)+y'=>0, '(-x)-y'=>0);
$exprA = $expr->substitute(x=>"x+h");
$exprB = Compute($exprA - $expr);
$exprC = Formula("$exprB/h");

####  Text of problem is removed ####
## Testing the student's answer to match $exprC but simplified.
ANS( $exprC->cmp()->withPostFilter(AnswerHints(
        sub {
            my ($correct, $student, $ans) = @_;
            my $testDeriv;
            eval {
                $testDeriv = $student->eval(x=>1-$a, h=>0);
            return ($student == $correct && !defined($testDeriv));
        } => ["Simplify to remove the discontinuity at h=0.", checkCorrect=>1],
    )) );
In reply to D. Brian Walton

Re: Testing for simplified form (division by zero)

by Davide Cervone -
You might want to consider using the parserDifferenceQuotient.pl macro file, which does essentially what you are asking for. See the comments at the top of the file, or at


for details. You will need to give $exprC as the actual reduced formula that you want the students to use instead of the one that contains division by h, however (which you should do anyway, so that if the students request the correct answer after the due date, it will give them something they would get credit for).

See if that does what you need. If not, you can use


which does error trapping. If there is an error, you should get an undefined return value if there is an error, and should be able to use $@ to get the actual error.

In reply to Davide Cervone

Re: Testing for simplified form (division by zero)

by D. Brian Walton -
Thank you.  I hadn't seen this parser.  I will use this approach.  But I appreciate knowing about Parser::Evaluate as well.