piffy
piffy

Reputation: 733

Full-range random number in Python

I'm generating a series of random floats using this line:

random.random()*(maxval-minval) + minval

I'm using it to add variable noise to a given variable, and the amount of noise added depends on a series of factors. In some cases, the noise should be so high that in practice the original value is lost, and I have a completely random value.

In this context, the code works works with finite values, but if I use "inf" it returns NaN. Is there a workaround to allow a continuos random range that might include the infinity? I don't want to tamper with os.random() as it is machine-specific.

Upvotes: 1

Views: 2939

Answers (4)

Sebastian Osiński
Sebastian Osiński

Reputation: 3004

As it was said before, you can't have uniform distribution over the whole real line, but you can use other random distributions which have real line support. Consider Cauchy distribution. It has 'heavy-tails', which simply means that there is a decent probability of getting very big numbers.

Upvotes: 2

WWhisperer
WWhisperer

Reputation: 97

As @Asad says, what you are trying is mathematically not quite sound. But what you could do, is the following:

Maybe this is what you are looking for.

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107287

After the discussion in comments i suggest the following :

>>> m=sys.maxint
>>> np.random.uniform(-m,m,5)
array([ -5.32362215e+18,  -2.90131323e+18,   5.14492175e+18,
        -5.64238742e+18,  -3.49640768e+18])

As is said the you can get the max integer with sys.maxint then you can use np.random.randint to get a random number between the maxint and -maxint.

Upvotes: 1

user1726343
user1726343

Reputation:

If you define a uniform random distribution over an infinite domain, the probability of any value in the domain being chosen is infinitesimal. What you're asking for doesn't make any mathematical sense.

Upvotes: 5

Related Questions