Is the following a pure function?
function test(min,max) {
return Math.random() * (max - min) + min;
}
My understanding is that a pure func
The simple answer to your question is that Math.random()
violates rule #2.
Many other answers here have pointed out that the presence of Math.random()
means that this function is not pure. But I think it's worth saying why Math.random()
taints functions that use it.
Like all pseudorandom number generators, Math.random()
starts with a "seed" value. It then uses that value as the starting point for a chain of low-level bit manipulations or other operations that result in an unpredictable (but not really random) output.
In JavaScript, the process involved is implementation-dependent, and unlike many other languages, JavaScript provides no way to select the seed:
The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.
That's why this function isn't pure: JavaScript is essentially using an implicit function parameter that you have no control over. It's reading that parameter from data calculated and stored elsewhere, and therefore violates rule #2 in your definition.
If you wanted to make this a pure function, you could use one of the alternative random number generators described here. Call that generator seedable_random
. It takes one parameter (the seed) and returns a "random" number. Of course, this number isn't really random at all; it is uniquely determined by the seed. That's why this is a pure function. The output of seedable_random
is only "random" in the sense that predicting the output based on the input is difficult.
The pure version of this function would need to take three parameters:
function test(min, max, seed) {
return seedable_random(seed) * (max - min) + min;
}
For any given triple of (min, max, seed)
parameters, this will always return the same result.
Note that if you wanted the output of seedable_random
to be truly random, you'd need to find a way to randomize the seed! And whatever strategy you used would inevitably be non-pure, because it would require you to gather information from a source outside your function. As mtraceur and jpmc26 remind me, this includes all physical approaches: hardware random number generators, webcams with lens caps, atmospheric noise collectors -- even lava lamps. All of these involve using data calculated and stored outside the function.