0

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
1
  • 1
    This seems clearly defined here en.wikipedia.org/wiki/Double_precision_floating-point_format. This defines the limits on floating-point numbers. 10**308 is pretty clearly defined as the upper limit. Is this what you're looking for? What more do you need to know? Commented Feb 22, 2012 at 15:19

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Figure out what the overflow on your machine is (should be sys.maxint). Then you can test away. What I've posted is an implementation of a theoretic discussion I had with someone, some time back
I'm testing it and seems that it works (in accordance to limit 10**308 as S.Lott commented), but wonder how you solved it in the theoretical discussion.
It was algebra. What you want to do is test that x * c (where c is a constant) will not overflow. You know (or can easily find) the overflow value. Then you do overflow/c if x is bigger than this number, then you're headed for an overflow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.