Search code examples
pythonnumpyuniform

numpy.random.uniform valid bounds for double


numpy.random.uniform returns a double between the specified low and high bounds.

I can use np.finfo(np.double) to get the min and max representable number, but if I use those values in numpy.random.uniform I get an error.

import numpy as np
info = np.finfo(np.double)
np.random.uniform(low=info.min, high=info.max)

OverflowError: Range exceeds valid bounds

Can someone shed light on what is going wrong here? What are the actual supported limits for low and high?

I tried getting the bounds for a double and inputting them to a rng intended for generating doubles, I expected these would be compatible.

Halving the bounds does work:

np.random.uniform(low=info.min/2, high=info.max/2)

So it suggests that either uniform cannot actually generate any double, or that the bounds returned by finfo are not inclusive.


Solution

  • uniform actually performs low + (high-low) * np.random.random().

    However high - low is not possible:

    info.max-info.min
    
    # RuntimeWarning: overflow encountered in scalar subtract info.max-info.min
    

    You found the limits of uniform. The difference between low and high should not exceed abs(info.max).

    np.random.uniform(low=0, high=info.max)              # valid
    np.random.uniform(low=info.min, high=0)              # valid
    np.random.uniform(low=info.min/2, high=info.max/2)   # valid
    rng.uniform(low=info.min*0.25, high=info.max*0.75)   # valid
    
    rng.uniform(low=info.min*0.501, high=info.max*0.501) # OverflowError