Follow

JavaScript ProcessingJS: random(a, b); can return b even if a!==b

According to the definition the random function should only be able to return b if a === b, the possible interval for the case a<b being [a, b). For most programs the value b will be returned very infrequently.

The bug also affects the function random(b); which can be used when a === 0.

Since this is a known bug, some students will insist that “if answer ===b” should be included as an option in the official JS project Magic 8 ball. This should be accepted as correct only if the student demonstrates an understanding of this being a bug, and a rare event for that particular project.

For those who want to know more about the bug

The bug has been fixed in the latest version of the ProcessingJS library, which has not been imported into Khan Academy.

Bug report: https://github.com/processing-js/processing-js/issues/244

In a worst case scenario the value b may be as common as a, see illustration by Bob Lyon:

Random failure demo

The issue is more common when a and b are very close numbers, either small numbers where the difference is considerably less than one, or very large numbers, where the fraction of a/b approaches 1.

Here is a program by Janice Holz which can be modified to check how often the bug occurs for your code, although it could take a while to experience it… Random: in 1000000 trials random(0.99999999999-1) rarely equals 1

 

Workaround

Bob Lyon’s solution from the program  Random patch

Comments:

If you are using

  • continuous random simulations or
  • random simulations in loops,
  • or in cases where |a/b| approaches |1|

it is necessary to guard against this bug.

If you have not learned about while loops yet, you are not likely to create programs where the bug will cause problems.

A solution based on while random number equals b, generate a new random number between a and b inclusive would give a skewed distribution, as can be seen from Chris Rennick’s program Spin-off of Random in 1000000 trials random(a,b) rarely equals b

Don’t try simply using the JavaScript function Math.random instead, as this has the same problem.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

 

August 13th 2017

Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request

Comments