Search code examples
pythonpython-3.xfloating-pointosx-yosemitepython-3.6

How do I use Python to generate a random number that is greater than a specified one?


By this I mean I need Python to generate any random number under one condition, it must be greater than the user defined number (lets say "x"), in other words it would be like saying x>num>infinity.

I tried using the random module but can't seem to figure anything out, as I tried something like this

import random
import math
inf=math.inf
x=15
random.randint(x,inf)

But that doesn't work because infinity is registered as a floating point number and the randint function only works with integers. I also tried something like this

import random
import math
inf=math.inf
x=15
random.uniform(x,inf)

This should work because the uniform function works with floating points, but it just ends up returning infinity every time.

This would mean that I need someway to get this done without using infinity (or math.inf) within my range, I just need the range to have a minimum (x) and no maximum at all. Any suggestions?

I'm running Python 3.6.0b4 on OS X Yosemite


Solution

  • There is no specific maximum integer. See this article

    Use sys.maxsize instead.

    sys.maxsize An integer giving the maximum value a variable of type Py_ssize_t can take. It’s usually 2^31 - 1 on a 32-bit platform and 2^63 - 1 on a 64-bit platform.

    To limit the upper bound to some lesser value, one could simply define a maximum that is less than that implied by sys.maxsize. For example, the 64-bit maximum signed integer 9,223,372,036,854,775,807 could be limited to 999,999,999,999,999L for 15 decimal places. You could just use that or any long integer less than that implied by sys.maxsize.