Documentation:WeBWorK/Problem Authoring Templates/Numeric Tolerance
Goal
Your problem has a scalar correct answer that is acceptable within some tolerance limits and that the student enters into a text field.
Solution
There are two parts to your code:
- In the problem set-up section, create a
Real
MathObject with the correct value and assign it to a known variable. E.g,$meaning_of_life = Real(42);
. - In the answer section, call the
ANS
command with the correct value'scmp
method, specifying the tolerance within it. There are two types of tolerance:- absolute: student's answer is accepted if the absolute difference with the correct answer is lower than the tolerance. For instance, if the correct value is 42, and absolute tolerance value is 0.5, then students' answers in the interval (41.5, 42.5) will be accepted. (Note that the interval is open: 41.5 and 42.5 will not be accepted as correct.) This is done as follows:
ANS($meaning_of_life->cmp(tolType => 'absolute', tolerance => 0.5))
. - relative: student's answer is accepted if the absolute difference of the correct value and student's answer divided by the correct value is lower than the tolerance. For instance, if the correct value is 42, and relative tolerance value is 0.1 (10%), then students' answers must be in the interval (37.8, 46.2). This is done as follows:
ANS($meaning_of_life->cmp(tolType => 'relative', tolerance => 0.1))
.
- absolute: student's answer is accepted if the absolute difference with the correct answer is lower than the tolerance. For instance, if the correct value is 42, and absolute tolerance value is 0.5, then students' answers in the interval (41.5, 42.5) will be accepted. (Note that the interval is open: 41.5 and 42.5 will not be accepted as correct.) This is done as follows:
Note
This method expects the tolerance interval to be symmetric around the correct value. If you want an asymmetric interval, you have to use a custom answer checker and do the comparison yourself. For instance, let's say you want to allow tolerance of -10% and +20% — i.e., if the correct answer is 42, then student answers in the interval (37.8, 50.4) are accepted:
ANS($meaning_of_life->cmp(checker => sub { my ($correct, $student) = @_; my $cv = $correct->value; my $sv = $student->value; return $sv > ($cv * .9) && $sv < ($cv * 1.2); }));
See the MAA wiki for details of configuring and using the built-in tolerance checking; and custom answer checkers.
Source code
Please download the following attachment to access the code in a single file. Unfortunately, the Wiki restricts filename extensions, so that it couldn't end in ".pg", which is what WeBWorK expects. You can rename it after downloading, or simply copy-and-paste its contents into the standard WeBWorK browser-based problem editor.