基于期望值生成随机数 [英] Generating random numbers based on an expected value

查看:66
本文介绍了基于期望值生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Java 编程,但遇到了一个可以求助的问题.基本上我需要用户输入他们期望某个事件在一定时间内发生的次数.该事件也需要一定的时间才能完成.综上所述,我需要使用随机数生成器来根据预期值决定事件是否应该发生.

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.

这是一个例子.假设事件需要 2 秒才能完成.用户说他们想要总共 100 秒,并且他们希望事件发生 25 次.现在这就是我所拥有的.Units 是时间单位,而 expectedLanding 是他们希望事件发生的次数.

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.

推荐答案

试试这个:

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

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

例如,如果您的概率为 0.25(4 分之 1),并且 nextDouble 返回 0 到 1 之间的随机数,则您的 nextDouble 需要小于(或等于)0.25 才能实现着陆.

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.

这篇关于基于期望值生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆