在java中随机生成整数数组的问题
我正在尝试生成一个包含 0 到 100000 之间的 N 个整数值的数组。
代码如下:
import java.util.*;
public class Main
{
public static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
int N;
System.out.println();
System.out.print("Enter an integer number: ");
N = input.nextInt();
int[] a = new int[N];
Random generator = new Random();
for(int i = 0; i < a.length; i++)
{
a[i] = generator.nextInt(100001);
}
}
}
我注意到,每次生成新数组时,数组中的大多数整数都是 5 位数字,有时有都是4位数字,很少有3位数字,但从来没有发现过2位或更少的数字。
我的实现是错误的吗?
I am trying to generate an array with N integer values between 0 and 100000.
Here is the code:
import java.util.*;
public class Main
{
public static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
int N;
System.out.println();
System.out.print("Enter an integer number: ");
N = input.nextInt();
int[] a = new int[N];
Random generator = new Random();
for(int i = 0; i < a.length; i++)
{
a[i] = generator.nextInt(100001);
}
}
}
What I notice that, at every time I generate new array, most of the integer numbers in the array is 5-digit numbers, sometimes there are 4-digit numbers, and rarely there are 3-digit numbers, but never happened that I found 2-digit or fewer numbers.
is my implementation wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
考虑每种数字有多少个:
所以 ~90%数字应为 5 位数字,只有约 1% 的数字应为 3 位或更少。它们会发生,但很少见。
Consider how many numbers there are of each kind:
So ~90% of your numbers should be 5-digit numbers, and only about 1% of the numbers should be 3 digits or fewer. They'll happen, but very rarely.
似乎错误的是你认为这在任何方面都很奇怪。
在0到100000之间的数字中,只有1个是6位数字,大约90%有5位数字,9%有4位数字,0.9%有3位数字,只有0.09%有1或2位数字。因此,考虑到均匀分布(
nextInt()
实现),您看不到它们或根本看不到它们一点也不奇怪。如果您想要不同的发行版,则必须自己实现。What seems to be wrong is your perception that this is in any way odd.
Of the numbers between 0 and 100000, there is only 1 that has 6 digits, about 90% have 5 digits, 9% have 4 digits, 0.9% have 3 digits, and only 0.09% have 1 or 2 digits. So given a uniform distribution (which
nextInt()
implements), it's not at all odd that you don't see them much or at all. If you want a different distribution, you'll have to implement it yourself.想想看......有
9 * 10 ^ (n-1)
个数字,其中有n
位。这意味着有 90000 个 5 位数字,而只有 900 个 3 位数字。平均而言,您预计每 100 个 5 位数字只能看到一个 3 位数字,每 10000 个 5 位数字只能看到一个个位数。Think about it... There are
9 * 10 ^ (n-1)
numbers withn
digits. That means there are 90000 5 digit numbers and only 900 3 digit numbers. On average you should expect to see only one 3 digit number for each 100 5 digit numbers, and only one single digit number per 10000 5 digit numbers.