Python random.uniform not generate 0 -
i want use random.uniform generate float in between [-2, 2], not generate 0, how in loop,
from random import uniform  flag = true  while flag:     if uniform(-2, 2) not 0:         flag = false   i wondering there better way it?
cheers
this more code review, briefly:
from random import uniform  while true:     if uniform(-2, 2) != 0.0:         break   is more pythonic / standard way (standard, in pattern occurs in other languages well).
it's rare flag variable necessary break out of (while) loop. perhaps when using double loop.
note: changed is not !=, , 0 0.0 (the latter more it's clear we're comparing float float).
 because you're comparing float int, they'll never same item. besides, comparing numbers using is bad idea:
>>> 2*3 6  # may work, don't rely on true >>> 10*60 600  # doesn't work false >>> 0 0   # sure, works... true >>> 0.0 0  # doesn't: float vs int false   of course, answer actual question if there other ways generate random numbers: dozen.
with list comprehension inside list comprehension*:
[val val in [uniform(-2, 2) in range(10)] if val != 0]using numpy:
vals = uniform(-2, 2, 10) vals = vals[vals!=0]
* don't want call nested, since feel belongs different double list comprehension.
Comments
Post a Comment