WeBWorK Main Forum

random number with many zero digits

random number with many zero digits

by Andras Balogh -
Number of replies: 4

I have a random number generated as $f0=non_zero_random(-9.5,9.5,0.1); 

It is displayed as 0.800000000000001

I know this comes from binary number representation, but I forgot how to suppress globally the extra digits showing.



In reply to Andras Balogh

Re: random number with many zero digits

by Alex Jordan -

If you make it a MathObject Real, then it will still be 0.800000000000001 for its value, but it will display as 0.8.

$f0 = Real(non_zero_random(-9.5, 9.5, 0.1));

BTW, I am not entirely sure that the "non_zero" will be honored here. Because within the algorithm it might not reach "0", as opposed to 0.000000000000001.  So it might not skip over what you want it to skip over. If you work with integers, you can avoid that possibility. Running from -95 to 95, then dividing by 10 should work:

$f0 = non_zero_random(-95, 95) / 10;

And making it a Real() too...why not?

$f0 = Real(non_zero_random(-95, 95) / 10);


In reply to Andras Balogh

Re: random number with many zero digits

by Danny Glin -

I'm not remembering a setting for determining the maximum number of digits to display.  It's possible that such a thing exists and I'm just not thinking of it.  If it does, it would only apply to MathObjects since I don't think you can do that to perl variables.

Here are a bunch of different ways to accomplish what you want in your scenario:

I recommend using $f0=non_zero_random(-95,95,1)/10;  This way the random value is generated as an integer and then converted to a decimal, so it should avoid the binary representation issue.  As an aside, you could use $f0=(random(-90,90,10)+random(1,9,1))/10; to ensure that all students receive a decimal value for $f0 rather than some receiving an integer.

Other ideas:

  • You can use sprintf to display a number in a specific format, like specifying a number of decimal places to show.  This doesn't fix the fact that the underlying value is still off by a small margin.
  • WeBWorK has two rounding functions:

  1. round($n) rounds $n to the nearest integer.
  2. Round($n,$m) rounds $n to $m decimal places.

In your case you could use $f0 = Round($f0,1);, but there are cases where rounding may give an undesired result.  e.g. if the value stored in the variable is 8.499999999999999 instead of 8.5, then rounding to the nearest integer will give 8 instead of 9.