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

V

Vincent Davis

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. The only
way I can thing of to do this is is with a while statement and that
seems more complicated than necessary. I would really like to keep it
on one line. How would I do that?

Thanks
Vincent Davis
 
S

Steven D'Aprano

Vincent said:
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?
 
D

Dennis Lee Bieber

Thanks for the response. But why would you set the mean to -1 to begin?
Consider it a typo, I suspect... from the use of such meaningless
parameters...

def __init__(self, mu, sigma):
x = -1
while 0 > x > 100:
x = normalvariate(mu, sigma)

Or see my other response...
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top