First some background on my situation:
I need a random triangular distribution and was planning on using Python's random.triangular. The following is the source code (Python 3.6.2):
def triangular(self, low=0.0, high=1.0, mode=None):
"""Triangular distribution.
Continuous distribution bounded by given lower and upper limits,
and having a given mode value in-between.
http://en.wikipedia.org/wiki/Triangular_distribution
"""
u = self.random()
try:
c = 0.5 if mode is None else (mode - low) / (high - low)
except ZeroDivisionError:
return low
if u > c:
u = 1.0 - u
c = 1.0 - c
low, high = high, low
return low + (high - low) * (u * c) ** 0.5
I reviewed the referenced wiki page and found that my desired use had a special case which simplifies things, and can be implemented with the following function:
def random_absolute_difference():
return abs(random.random() - random.random())
Doing some quick timings reveals a significant speedup with the simplified version (this operation will be repeated far more than a million times each time my code runs):
>>> import timeit
>>> timeit.Timer('random.triangular(mode=0)','import random').timeit()
0.5533245000001443
>>> timeit.Timer('abs(random.random()-random.random())','import random').timeit()
0.16867640000009487
So now for the question: I know python's random module only uses pseudo-randomness, and random.triangular uses one random number while the special case code uses 2 random numbers. Will the special case results be significantly less random because they use 2 consecutive calls to random, while random.triangular only uses one? Are there any other unforeseen side effects of using the simplified code?
Edit: In reference to this solution to a different question, I created histogram plots for both distributions, showing that they are comparable: