Search code examples
python-3.xrandomuniform

Python random.uniform not generate 0


I want to use random.uniform to generate a float in between say [-2, 2], but not generate 0, this is how I do it in a loop,

from random import uniform

flag = True

while flag:
    if uniform(-2, 2) is not 0:
        flag = False

I am wondering is there better way to do it?

cheers


Solution

  • This is more something for Code Review, but very briefly:

    from random import uniform
    
    while True:
        if uniform(-2, 2) != 0.0:
            break
    

    is probably the more Pythonic / standard way to do this (standard, as in that this pattern occurs in other languages as well).

    It's rare that a flag variable is necessary to break out of a (while) loop. Perhaps when using a double loop.

    Note: I changed your is not to !=, and your 0 to 0.0 (the latter is more so that it's clear we're comparing a float to a float).
    Because you're comparing a float to an int, so they'll never be the same item. Besides, comparing numbers using is is a bad idea:

    >>> 2*3 is 6  # this may work, but don't rely on it
    True
    >>> 10*60 is 600  # this obviously doesn't work
    False
    >>> 0 is 0   # sure, this works...
    True
    >>> 0.0 is 0  # but this doesn't: float vs int
    False
    

    Of course, to answer the actual question if there are other ways to generate those random numbers: probably a dozen.

    • With a list comprehension inside a list comprehension*:

      [val for val in [uniform(-2, 2) for i in range(10)] if val != 0]
      
    • Using numpy:

      vals = uniform(-2, 2, 10)
      vals = vals[vals!=0]
      

    * I don't want to call it nested, since I feel that belongs to a slightly different double list comprehension.