Java:在x%的时间里做某事

Java:在x%的时间里做某事,java,Java,我需要几行Java代码,它们在x%的时间内随机运行命令 伪代码: boolean x = true 10% of cases. if(x){ System.out.println("you got lucky"); } 你只需要这样的东西: Random rand = new Random(); if (rand.nextInt(10) == 0) { System.out.println("you got lucky"); } 下面是一个完整的例子来衡量它: import

我需要几行Java代码,它们在x%的时间内随机运行命令

伪代码:

boolean x = true 10% of cases.

if(x){
  System.out.println("you got lucky");
}

你只需要这样的东西:

Random rand = new Random();

if (rand.nextInt(10) == 0) {
    System.out.println("you got lucky");
}
下面是一个完整的例子来衡量它:

import java.util.Random;

public class Rand10 {
    public static void main(String[] args) {
        Random rand = new Random();
        int lucky = 0;
        for (int i = 0; i < 1000000; i++) {
            if (rand.nextInt(10) == 0) {
                lucky++;
            }
        }
        System.out.println(lucky); // you'll get a number close to 100000
    }
}

如果你想要34%的数据,你可以使用rand.nextInt100<34。

你必须先定义时间,因为10%是一个相对的度量

例如,x每5秒为真


或者你可以使用一个随机数生成器,从1到10进行均匀采样,如果他对1进行采样,你可以总是做一些事情。

你可以总是生成一个随机数,默认情况下,它在0到1之间,我相信,并检查它是否是如果你指的是代码正在执行的时间,那么你希望在代码块中得到一些东西,这是整个块执行时间的10%,您可以执行以下操作:

Random r = new Random();

...
void yourFunction()
{
  float chance = r.nextFloat();

  if (chance <= 0.10f)
    doSomethingLucky();
}
当然,0.10f代表10%,但你可以调整它。像每一个PRNG算法一样,这是按平均使用率计算的。除非您的函数被调用了合理的次数,否则您不会得到接近10%。

您可以使用。您可能希望为其设置种子,但默认设置通常就足够了

Random random = new Random();
int nextInt = random.nextInt(10);
if (nextInt == 0) {
    // happens 10% of the time...
}
你可以试试这个:


public class MakeItXPercentOfTimes{

    public boolean returnBoolean(int x){
        if((int)(Math.random()*101) <= x){ 
            return true; //Returns true x percent of times.
        }
    }

    public static void main(String[]pps){
        boolean x = returnBoolean(10); //Ten percent of times returns true.
        if(x){
            System.out.println("You got lucky");
        }
    }
}

要以代码为基础,您可以这样做:

ifMath.random<0.1{ System.out.println你很幸运; }
FYI Math.random使用random的静态实例

,因为nextFloat可能导致零,所以比较应严格小于。换句话说,使用这是不正确的。这只是一个错误的假设,浮点不是精确的数字,所以在这种情况下使用严格的比较不会改变任何事情,也因为随机序列是由int值生成的。我要求您提供一个片段,表明使用just<运算符可以得到更正确的接近10%的结果:好吧,我同意在10%的特定情况下,关系并不重要。但是50%怎么样?还是75%?我的观点是,对于一般的正确性,你应该使用@erickson:我只是为了好玩,用0.01步测试了从0.01到0.99的整个范围,用100万次投掷尝试了1000次每个概率值,但没有任何区别。如果使用可以用二进制浮点完全表示的chabce,可能会有很小的差异,但不确定。这是有问题的,您不应该将调用.random的结果强制转换为int,因为这样会引入非随机偏差。相反,请使用适当的随机方法,例如.nextInt,它可以正确处理这些偏差。

public class MakeItXPercentOfTimes{

    public boolean returnBoolean(int x){
        if((int)(Math.random()*101) <= x){ 
            return true; //Returns true x percent of times.
        }
    }

    public static void main(String[]pps){
        boolean x = returnBoolean(10); //Ten percent of times returns true.
        if(x){
            System.out.println("You got lucky");
        }
    }
}