WeBWorK Problems

Squaring negative numbers using "Compute"

Squaring negative numbers using "Compute"

by Hedley Pinsent -
Number of replies: 2
Tale of two "Compute"s:

"Compute" gives incorrect answers when squaring negative numbers.
Presumedly my packages are up to date.

Regards - hp



$h = -4 ;
$test1 = Compute ("$h **2"); # gives -16
$test2 = Compute ("$h^2"); # gives -16
$test3 = $h **2 ; # gives correct answer 16


$test1 $PAR
$test2 $PAR
$test3 $PAR

In reply to Hedley Pinsent

Re: Squaring negative numbers using "Compute"

by D. Brian Walton -
Compute interprets the literal string. The way Perl interprets the code in the first two examples are as strings interpreted as a formula, literally as you gave it "-4 ^2". Using order of operations, the power is applied to 4 and then the answer has a sign change.

The last example is mathematical only, and Perl squares the number -4.

You always need parentheses around variables that are possibly negative, as in "($a)^2". You also need to be careful about multiplication like "$a $b" which will be interpreted as subtraction if $b is a negative number, "$a*$b"


In reply to D. Brian Walton

Re: Squaring negative numbers using "Compute"

by Hedley Pinsent -
Thanks Brian and Alex (Jordan)

It's all sorted out now.

Alex's comments made it to my mailbox but not the forum (presumably a technical issue) and I have taken the liberty of including them below. The only thing I will add is that Compute($h **2) works but Compute($h^2) will not.

So many layers - so exciting - I think I will not think about it too much and let it seep in.


Hi Hedley,

When you use:
Compute ("$h **2");
The quotes are turning "$h **2" into a string first, by turning each Perl variable into its string format. So you are actually asking for:
Compute ("-4 **2");
which should be -16.
Instead, I think you could use:
Compute ("($h) **2");
Compute ($h **2);
Real($h **2);