Java 生成数学随机数的问题,0 或 1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28401093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Problems Generating A Math.random Number, Either 0 or 1
提问by alannm37
I've seen this question posted in a lot of times on this website and believe me I have looked through so many of them and so many YouTube videos and nothing has ended up working for me. As the title says I want a random number, either 0 or 1 and then that will be returned to main() as in my code below.
我在这个网站上多次看到这个问题,相信我,我已经浏览了很多这样的问题和很多 YouTube 视频,但最终没有任何效果对我有用。正如标题所说,我想要一个随机数,0 或 1,然后它将返回到 main(),如下面的代码所示。
import java.util.Scanner;
public class Exercise8Lab7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numFlips = 0;
int heads = 0;
int tails = 0;
String answer;
System.out.print("Please Enter The Number Of Coin Tosses You Want: ");
numFlips = input.nextInt();
for(int x = 1;x <= numFlips; x++){
if(coinToss() == 1){
answer = "Tails";
tails++;
}
else{
answer = "Heads";
heads++;
}
System.out.print("\nCoin Toss " + x + ": " + answer);
}
System.out.println("\n\n====== Overall Results ======" +
"\nPercentage Of Heads: " + (heads/numFlips)*100 + "\nPercentage Of Tails: " + (tails/numFlips)*100);
}
public static int coinToss(){
double rAsFloat = 1 * (2 + Math.random( ) );
int r = (int)rAsFloat;
return r;
}
}
Many solutions had been suggested to use the util.Random option which I have done and works perfectly but I want to sort out why I can't get this to work. Obviously I want the number to be an int myself so I convert it to an int after the random number has been generated. But no matter what I add or multiply the Math.random() by, it will always all either be Heads or all either be Tails. Never mixed.
许多解决方案已被建议使用 util.Random 选项,我已经完成并完美地工作,但我想弄清楚为什么我不能让它工作。显然,我希望这个数字自己是一个 int,所以我在生成随机数后将它转换为一个 int。但无论我添加或乘以 Math.random() 什么,它总是要么都是正面,要么都是尾巴。从来不混。
Any help appreciated!
任何帮助表示赞赏!
回答by alannm37
You could use boolean values of 0 or 1 based on value of Math.random()
as a double between 0.0 and 1.0 and make the random generator much simpler. And you can get rid completely of the coinToss()
method.
您可以根据 0Math.random()
和 1.0 之间的双精度值使用 0 或 1 的布尔值,并使随机生成器更简单。你可以完全摆脱这种coinToss()
方法。
if(Math.random() < 0.5) {
answer = "Tails";
tails++;
}
Remove the coin toss method and replace the first conditional with the code above.
去掉抛硬币方法,用上面的代码替换第一个条件。
Math.random();
by itself will return a value between 0.0 and less than 1.0. If the value is in the lower half, [0.0, 0.5), then it has the same probability of being in the upper half, [0.5, 1.0). Therefore you can set any value in the lower half as true and upper as false.
Math.random();
本身将返回一个介于 0.0 和小于 1.0 之间的值。如果值在下半部分,[0.0, 0.5),那么它在上半部分的概率相同,[0.5, 1.0)。因此,您可以将下半部分的任何值设置为 true,将上半部分设置为 false。
回答by Damian Nikodem
its not working because of the integer math you are using, the call to 2+ Math.Random is pretty much always giving you a answer between 0.0 and 1.0.
由于您使用的整数数学,它不起作用,对 2+ Math.Random 的调用几乎总是给您一个介于 0.0 和 1.0 之间的答案。
so assuming that you recieve 0.25 as your result your maths is as follows
所以假设你收到 0.25 作为你的结果,你的数学如下
double d = 1* (2 + 0.25); // (result = 2
Then you are checking to see if your result == 1 ( which it never will. )
然后你检查你的结果是否 == 1(它永远不会。)
A better result would be to declare java.util.Random as a class variable and call random.nextBoolean() and simply perform your heads/tails calculation on that.
更好的结果是将 java.util.Random 声明为类变量并调用 random.nextBoolean() 并简单地对其执行正面/反面计算。
If you were to continue to use Math.random() and lets say
如果你继续使用 Math.random() 并让我们说
return Math.random() < 0.5
Your results would be ever so slightly skewed due to the fact that Math.random() cannot return 1.0, due to the fact that the java API specification states:
由于 Java API 规范规定,由于 Math.random() 无法返回 1.0,因此您的结果会稍微偏斜:
"Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0."
“返回一个带正号的双精度值,大于或等于 0.0 且小于 1.0。”
回答by ajb
Math.random()
returns a random float in the range [0.0,1.0)--that means the result can be anything from 0 up to but not including1.0.
Math.random()
返回 [0.0,1.0) 范围内的随机浮点数 - 这意味着结果可以是从 0 到但不包括1.0 的任何值。
Your code
你的代码
double rAsFloat = 1 * (2 + Math.random( ) );
will take this number in the [0.0,1.0) range; adding 2 to it gives you a number in the [2.0,3.0) range; multiplying it by 1 does nothing useful; then, when you truncate it to an integer, the result is always 2.
将在 [0.0,1.0) 范围内取这个数字;添加 2 给你一个 [2.0,3.0) 范围内的数字;乘以 1 没有任何用处;然后,当您将其截断为整数时,结果始终为 2。
To get integers from this kind of random function, you need to figure out how many different integers you could return, then multiply your random number by that. If you want a "0 or 1" answer, your range is 2 different integers, so multiply Math.random()
by 2:
要从这种随机函数中获取整数,您需要弄清楚可以返回多少个不同的整数,然后将您的随机数乘以它。如果你想要一个“0 或 1”的答案,你的范围是 2 个不同的整数,所以乘以Math.random()
2:
double rAsFloat = 2 * Math.random();
This gives you a random number in the range [0.0,2.0), which can then be 0 or 1 when you truncate to an integer with (int)
. If, instead, you wanted something that returns 1 or 2, for example, you'd just add 1 to it:
这会为您提供范围 [0.0,2.0) 中的随机数,当您使用 截断为整数时,它可以是 0 或 1 (int)
。相反,如果您想要返回 1 或 2 的值,例如,您只需向其添加 1:
double rAsFloat = 1 + 2 * Math.random();
I think you've already figured out that the Random
class gives you what you want a lot more easily. I've decided to explain all this anyway, because someday you might work on a legacy system in some old language where you really do need to work with a [0.0,1.0) random value. (OK, maybe that's not too likely any more, but who knows.)
我认为您已经发现该Random
课程更容易为您提供您想要的东西。无论如何,我决定解释所有这些,因为有一天你可能会使用某种旧语言在遗留系统上工作,而你确实需要使用 [0.0,1.0) 随机值。(好吧,也许这不太可能了,但谁知道呢。)
回答by DzenDzimon
Try this) It will generate number 0or 1
试试这个)它会生成数字0或1
Math.round( Math.random() ) ;
回答by Kanak Lata
(int)(Math.random()*2) also works fine in this case
(int)(Math.random()*2) 在这种情况下也能正常工作
回答by Java Main
The problem can be translated to boolean generation as follow :
该问题可以转换为布尔值生成,如下所示:
public static byte get0Or1 {
Random random = new Random();
boolean res= random.nextBoolean();
if(res)return 1;
else return 0;
}
回答by Super Best
for(int i=0;i<100;i++){
System.out.println(((int)(i*Math.random())%2));
}
use mod it will help you!
使用mod它会帮助你!
回答by Pier Betos
Wierd that no one is using a modulo division for the random number. This is the simplest implementation you can get:
奇怪的是,没有人对随机数使用模除法。这是您可以获得的最简单的实现:
Random rand = new Random();
int randomValue = rand.nextInt() % 2;
回答by balaji
Math.round(Math.random()) will return either 0.0 and 1.0. Since both these values are well within the limits of int range they can be casted to int.
Math.round(Math.random()) 将返回 0.0 和 1.0。由于这两个值都在 int 范围的限制内,因此可以将它们强制转换为 int。
public static int coinToss(){
return (int)Math.round(Math.random());
}