Reputation: 559
I recently discovered the ECMAScript Spec, which I was able to use to answer a question I've had about Math.random()
for a while; namely whether or not it would ever generate 0
without the help of Math.floor()
.
The ECMAScript Spec specifies that 0 <= Math.random() < 1
, unlike literally anyone else for some reason. I hopped over to the console and ran a test before saving it in my notes but noticed that statement reduces to false
.
Below is a function that tests everything about comparison statements that I thought might be causing this lie. I call the function twice to generate two arrays of Boolean values, and the results seem to imply that literally this statement: 0 <= Math.random() < 1
- and this statement alone, returns FALSE
where it should return TRUE
. Especially when you consider bonus round where I test the exact same statement but with an additional comparison tacked onto the end, and it also returns true
function getTruths( a, b, c ) {
return [
a + 1 < b + 1,
a + 1 < c + 1,
b + 1 < c + 1,
a + 1 < b + 1 < c + 1,
a + 0 < b + 0,
a + 0 < c + 0,
b + 0 < c + 0,
a + 0 < b + 0 < c + 0
];
}
function demonstrate() {
// array of truth
console.log( getTruths( 0, 1, 2 ) );
// array of lies
console.log( getTruths( 0, 0.5, 1 ) );
// bonus round
return [ 0 < 0.5 < 1 < 1.5 ];
}
demonstrate();
So I did some more plucking around and learned that it isn't just that. it seems that a
and b
can actually be any value lower that one and equal to or greater than zero, just as long as b
is still bigger than a
, and c
is still equal to 1
of course... and given those parameters, no matter what, the return is still FALSE
. If you add 1
to everything though suddenly you're in good shape again, just as in the function provided above.
Anyway can someone explain this to me? Thanks.
Upvotes: 0
Views: 167
Reputation: 413737
a < b < c
is interpreted as
(a < b) < c
The result value from a relational operator like <
is a boolean, either true or false. If c
is a number, then, that boolean will be converted to a number, either 1 (true
) or 0 (false
). Thus c
is compared to either 0 or 1, not the values of either a
or b
.
The proper way to write "is b
strictly between a
and c
" is
a < b && b < c
Upvotes: 4