0

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.

justin henricks
  • 467
  • 3
  • 6
  • 17

2 Answers2

0

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.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
0

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
Andrew Mao
  • 35,740
  • 23
  • 143
  • 224