WeBWorK Problems

arithmetic syntax in Compute

arithmetic syntax in Compute

by Murray Eisenberg -
Number of replies: 2
Error at line 46: In a question I've loaded the usual macros, including MathObjects.pl. I have the following initializations after that:

36 $bhalf = random(2,10,1);
37 $b = Compute("2*$bhalf");
39 $index = random(1,10,1);
40 @increments = (2,3,5,6,7,8,10,11,12,13);
41 $k = @increments[$index];
42 # coefficient of y
43 $c = Compute("$k + ($b**2)/4");
45 $lambda = Compute("-$bhalf");
46 $discrim = Compute("-4*$k");
47 $negdiscrim = Compute("4*$k");

Yet I get the following error message when viewing as a student:
Missing operand after '*'; see position 3 of formula at line 93 of [PG]/macros/Parser.pl Died within main::Formula called at line 93 of [PG]/macros/Parser.pl from within main::Compute called at line 46 of [TMPL]/Local/Murray_PhaseAmplitudeForm.pg

Oddly, I'm getting the error only when I view this as some students and not others. The question was already deployed in a set. Most students encountered no error, apparently (and already got it correct). Yet a couple are running into the error.

Is there something in Perl syntax I'm missing here?
In reply to Murray Eisenberg

Re: arithmetic syntax in Compute

by Michael Gage -
The perl syntax you are missing is that array indexing begins at 0.

You want to choose your index randomly between 0 and 9 not 1 and 10.

If $index has the value 10 then

$k = @increments[$index]

places an empty string/undefined value in $k and that causes the error that is reported.

Also (and this is one of the idiosyncrasies of perl) the line should

$k = $increments[$index];

since you are placing a scalar value into $k, not an array with one element. (For more on this see "Learning Perl" by "Randal Schwartz")
In reply to Michael Gage

Re: arithmetic syntax in Compute

by Murray Eisenberg -
Thanks! Evidently that's why only a couple students got the error, because they were the unlucky ones for whom the index went out of bounds. I forgot about the index-origin. And given my long experience as an APL and J programmer, that's almost unforgivable!