WeBWorK Problems

Rounding in Random Numbers

Rounding in Random Numbers

by Genevieve Toutain -
Number of replies: 3
I think I posted this in the wrong place yesterday, so I thought I would try it over here.   I am authoring a question that includes a random one digit decimal between -10 and 10, hence:

$a = random(-10,10,.1);


I just happened to have seed 1612, and when printing out $a in the problem, instead of printing -0.02 (as I suspect it wanted to), it is printing out -0.1999999999. 


I'm having the same issue with 


random(-5,5,.1); with seed 4252


printing out -0.899999999999. 


Any ideas on what I should do here?  Is there a way to restrict how many decimal places WeBWork displays?  Is this a known issue?  I tried searching the forums to not much avail. 


I've gotten around this by replacing it with 


$a = random(-10,10)+random(0,1,.1);


which while technically not the same serves my purposes just fine.  I'm a little concerned there are other lurking decimal issues I haven't run into yet, and my students are not sophisticated enough not to be frightened by long decimals. 

In reply to Genevieve Toutain

Re: Rounding in Random Numbers

by Alex Jordan -
Try using Math Objects, and set
$a = Real($a);

This will induce rounding to six figures. (The reason for the bad decimal in the first place is machine rounding error between base 2 and base 10.)
In reply to Genevieve Toutain

Re: Rounding in Random Numbers

by Danny Glin -
This is one of the dangers of floating point operations.  Any time you are doing arithmetic with decimal numbers, you risk these errors.

In my experience, the following code hasn't caused any of these issues:
$a = random(-100,100) / 10;

Danny