Prevent overflow errors when multiplying and powering in Python
-
29-10-2019 - |
Question
How would you prevent the errors when calling function biased_random defined below and what are the limits for arguments scale
and bias
to hold for preventing problems with big or small numbers?
def biased_random(scale, bias):
return random.random() ** bias * scale
>>> sum(biased_random(1000, 10) for x in range(100)) / 100
64.94178302276364
>>> sum(biased_random(1000, 100000) for x in range(100)) / 100
0.0
>>> sum(biased_random(1000, 0.002) for x in range(100)) / 100
998.0704866851909
Solution
I'd use sys.maxint
to figure out what the overflow point is. Then divide or nth-root it and compare with the number that you have:
r = random.random()
if sys.maxint ** (1.0/bias) < r:
print "overflow imminent"
elif sys.maxint/float(scale) < r ** bias:
print "overflow imminent"
else:
print "overflow unlikely. To infinity, and beyond..."
Hope this helps
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow