我如何在代码中实现这一点 我正在接受三个单独的浮点数的用户输入,这些浮点数必须加到一个(即 .333333、.333333、.333333)这些数字是数字(-1,0,1)的概率随机挑选的。
if( new Random().nextDouble() <= 0.333334){array[i]=randomNumber(-1,0,1)
?
或类似的规定?
我如何在代码中实现这一点 我正在接受三个单独的浮点数的用户输入,这些浮点数必须加到一个(即 .333333、.333333、.333333)这些数字是数字(-1,0,1)的概率随机挑选的。
if( new Random().nextDouble() <= 0.333334){array[i]=randomNumber(-1,0,1)
?
或类似的规定?
三个浮点数加起来正好为 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};
}
问题?