简体   繁体   English

三个浮点数的概率

[英]Probability of three floating point numbers

How can I implement this into code I am taking a user input of three separate floats that must add to one (ie .333333,.333333,.333333) those numbers are the probability of a number (-1,0,1) being picked at random. 我如何将其实现为代码?我正在接受用户输入的三个独立的浮点数,这些浮点数必须加到一个(即.333333,.333333,.333333)上,这些数字是数字(-1,0,1)为随机选择。

if( new Random().nextDouble() <= 0.333334){array[i]=randomNumber(-1,0,1) ? if( new Random().nextDouble() <= 0.333334){array[i]=randomNumber(-1,0,1)

Or something along those lines? 或类似的规定?

The likelihood that three floats will add to exactly 1.0 is very low, because many (most) real numbers cannot be represented exactly as floats. 三个浮点数精确加到1.0的可能性非常低,因为许多(大多数)实数不能精确地表示为浮点数。 The best you could do is enter two numbers and calculate the third, which would guarantee that they would add up to 1.0. 您可能要做的最好是输入两个数字并计算第三个数字,这将保证它们的总和为1.0。

public static void main(String[] args) {
    double[] probs = readProbabilities();
    double random = new Random().nextDouble();
    int randomNumber;
    if (random <= probs[0]) {
        randomNumber = -1;
    } else if (random <= (probs[0] + probs[1])) {
        randomNumber = 0;
    } else {
        randomNumber = 1;
    }
    System.out.println("Random Number is " + randomNumber);
}

public static double[] readProbabilities() {
    Scanner sc = new Scanner(System.in);
    double first, second, third;
    System.out.print("Please insert 1st probability: ");
    first = sc.nextDouble();
    while (first < 0.0 || first > 1.0) {
        System.out.print("Must be between 0.0 and 1.0, try again: ");
        first = sc.nextDouble();
    }
    System.out.print("Please insert 2nd probability: ");
    second = sc.nextDouble();
    while (second < 0.0 || (first + second) > 1.0 ) {
        System.out.print("Must be between 0.0 and " + (1.0 - first) + ":");
        second = sc.nextDouble();
    }
    third = 1.0 - (first + second);
    System.out.println("3rd Possibility is " + third);
    return new double[] {first, second, third};
}

Questions? 有什么问题吗

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM