calculating a self.value, self.randomnum = normalvariate(x, y)

Steven D'Aprano steve at REMOVETHIS.cybersource.com.au
Sat Jun 20 10:35:19 EDT 2009


Vincent Davis wrote:

> I currently have something like this.
> 
> class applicant():
>     def __int__(self, x, y):
>         self.randomnum = normalvariate(x, y)
> then other stuff
> 
> x, y are only used to calculate self.randomnum   and this seems to
> work. But I want self.randomnum to be 0 <= randomnum <= 100. 

Then it isn't a normal variate.


> The only 
> way I can thing of to do this is is with a while statement and that
> seems more complicated than necessary. 

Why? It's a perfectly simple procedure:

def __int__(self, x, y):
    x = -1
    while not 0 <= x <= 100:
        x = normalvariate(x, y)
    # do other stuff

That is the correct way to truncate a normal distribution.


Alternatively, truncate values past the end-points, but this will distort
the random distribution significantly:

x = max(0, min(100, normalvariate(x, y)))

You probably don't want that, as it will cause far more 0 and 100 values
than you would otherwise expect.


> I would really like to keep it 
> on one line. How would I do that?

Why? Is the enter key on your keyboard broken?




-- 
Steven




More information about the Python-list mailing list