rubyonrailsin

A Ruby and Rails talk

Sunday, March 21, 2010


Re: [Rails] Calculate Probability?

by rubyonrailsin 0 comments

Tag


Share this post:
Design Float
StumbleUpon
Reddit

The Sun, 21 Mar 2010 17:12:02 +0100,
Heinz Strunk <lists@ruby-forum.com> wrote:

> Hello,
>
> I'm working with probability and Ruby doesn't really does as I want.
> Just to make it easier to understand I'll focus on the problem.
>
> I have some event that should occur in 20% of all events. I thought
> I'd make it easy by just using rand like following:
> num = 20 - rand(100)
> if(num > 0)
> do_stuff
> end
>
> But "do_stuff" is by far not being called as often as I would like it
> to. Is there any method or something that is more accurate with that
> kind of stuff?

As said in another answer, this is convoluted code, simply testing
rand(100) < 20
is ok.

To answer your original question, rand implementations don't do what
most developers think they do : they are pseudo-random number
generators and the randomness is not guaranteed for only one call to
rand in a whole program.

If you try to get a random value only once in your program, you should
feed the number generator a truly random value (for example read
4 bytes from /dev/urandom on a modern Unix box and feed them as an
Integer to the generator through Kernel.srand).

Lionel

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment

Subscribe feeds via e-mail

Blog Archive