Generating random numbers based on an expected value

耗尽温柔 提交于 2019-12-13 02:54:57

问题


I am programming in java and I have come across a problem I could use some help with. Basically I need the user to enter how many times they expect a certain event to happen in a certain amount of times. The event takes a certain amount of time to complete as well. With all that said I need to use a random number generator to decide whether or not the event should happen based on the expected value.

Here's an example. Say the event takes 2 seconds to complete. The user says they want 100 seconds total and they expect the event to happen 25 times. Right now this is what I have. Units is the units of time and expectedLanding is how many times they would like the event to take place.

double isLandingProb = units/expectedLanding;
double isLanding = isLandingProb * random.nextDouble();
if(isLanding >= isLandingProb/2){
//do event here
}

This solution isn't working, and I'm having trouble thinking of something that would work.


回答1:


Try this:

double isLandingProb = someProbability;
double isLanding = random.nextDouble();

if(isLanding <= isLandingProb){
    //do event here
}

For example, if your probability is .25 (1 out of 4), and nextDouble returns a random number between 0 and 1, then your nextDouble needs to be less than (or equal to) .25 to achieve a landing.




回答2:


Given an event that takes x seconds to run, but you want it to run on average once every y seconds, then it needs to execute with probability x/y. Then the expectation of the number of seconds the event is running over y seconds is x = one event.

int totalSeconds;
int totalTimes;
double eventTime;

double secondsPerEvent = 1.0d * totalSeconds / totalTimes;
if( eventTime > secondsPerEvent ) throw new Exception("Impossible to satisfy");

double eventProbability = eventTime / secondsPerEvent;

if( eventProbability < random.nextDouble() )
    //  do event


来源:https://stackoverflow.com/questions/15255139/generating-random-numbers-based-on-an-expected-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!