Skip to content
This repository has been archived by the owner on Dec 5, 2018. It is now read-only.

Improve random() #269

Merged
merged 3 commits into from Oct 12, 2016
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 7 additions & 7 deletions src/P5Functions/Math.js
Expand Up @@ -425,14 +425,14 @@ module.exports = function withMath(p, undef) {
* @see randomSeed
* @see noise
*/
p.random = function() {
if(arguments.length === 0) {
return internalRandomGenerator();
p.random = function(aMin, aMax) {
if (arguments.length === 0) {
aMax = 1;
aMin = 0;
} else if (arguments.length === 1) {
aMax = aMin;
aMin = 0;
}
if(arguments.length === 1) {
return internalRandomGenerator() * arguments[0];
}
var aMin = arguments[0], aMax = arguments[1];
if (aMin === aMax) {
return aMin;
}
Expand Down
10 changes: 5 additions & 5 deletions test/unit/random.pde
Expand Up @@ -48,15 +48,15 @@ randomSeed(14);
var minSample = 30, maxSample = 40;
for(int i=0;i<attempts;++i) {
var sample = r1[i];
if(sample < 0 || sample >= 1) _checkTrue(false); // bad random with no args
if (!(sample < 1 && sample >= 0)) _checkTrue(false); // bad random with no args
Copy link
Member

@Pomax Pomax Oct 10, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hm, the old test code should have already done the right thing: if sample is less than 0 or it's greater or equal to one, it should throw an error, by exploiting the fact that false will obviously fail a checkTrue check.

Can you explain how this rewrite improves on it? (it has certainly become harder to understand at a glance with this new ordering and effective double negative)

}
for(int i=0;i<attempts;++i) {
var sample = random(maxSample);
if(sample < 0 || sample >= maxSample) _checkTrue(false); // bad random with one arg
if (!(sample < maxSample || sample >= 0)) _checkTrue(false); // bad random with one arg
}
for(int i=0;i<attempts;++i) {
var sample = random(minSample, maxSample);
if(sample < minSample || sample >= maxSample) _checkTrue(false); // bad random with two arg
if (!(sample < maxSample && sample >= minSample)) _checkTrue(false); // bad random with two arg
}

double r,
Expand All @@ -67,7 +67,7 @@ double r,
boolean failed = false;
for (int i=0; i<100000; i++) {
r = random(a, b);
if (r >= b || r < a) {
if (!(r < b && r >= a)) {
failed = true;
break;
}
Expand All @@ -80,7 +80,7 @@ double r,
boolean failed = false;
for (int i=0; i<100; i++) {
r = random(b);
if (r >= b || r < 0) {
if (!(r < b && r >= 0)) {
failed = true;
break;
}
Expand Down