Java 随机数生成器给出了奇怪的结果
我有一个类,它首先存储鼠标光标的当前坐标,然后创建两个随机整数x和y都在-10和10之间,然后水平和垂直移动鼠标光标,移动量分别等于生成的数字Java 随机数生成器给出了奇怪的结果,java,random,cursor,Java,Random,Cursor,我有一个类,它首先存储鼠标光标的当前坐标,然后创建两个随机整数x和y都在-10和10之间,然后水平和垂直移动鼠标光标,移动量分别等于生成的数字 public class Test { private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); private static int width= (int) screenSize.getWidth
public class Test {
private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
private static int width= (int) screenSize.getWidth();
private static int height=(int) screenSize.getHeight();
private static int currentX=(int) MouseInfo.getPointerInfo().getLocation().getX();
private static int currentY =(int) MouseInfo.getPointerInfo().getLocation().getY();
public static void main(String[] args) throws java.awt.AWTException {
Robot robot=new Robot();
Random random = new Random();
int xMove;
int yMove;
int[] resultArray=new int[10000];
for (int i=0; i<10000; i++) {
refreshCoords();
xMove=random.nextInt(20) - 10; // - 10 to 10
yMove=random.nextInt(20) - 10;
robot.mouseMove(currentX + xMove, currentY + yMove);
resultArray[i]=xMove;
}
System.out.println(sumArray(resultArray)); //returns - 4000/-5000
}
private static void refreshCoords() {
currentX=(int) MouseInfo.getPointerInfo().getLocation().getX();
currentY=(int) MouseInfo.getPointerInfo().getLocation().getY();
}
private static int sumArray(int[] resultArray) {
int result=0;
for (int i=0; i<resultArray.length; i++) {
result+=resultArray[i];
}
return result;
}
}
公共类测试{
私有静态维度screenSize=Toolkit.getDefaultToolkit().getScreenSize();
私有静态int-width=(int)screenSize.getWidth();
私有静态int height=(int)screenSize.getHeight();
私有静态int currentX=(int)MouseInfo.getPointerInfo().getLocation().getX();
私有静态int currentY=(int)MouseInfo.getPointerInfo().getLocation().getY();
公共静态void main(字符串[]args)抛出java.awt.AWTException{
机器人=新机器人();
随机=新随机();
int xMove;
int yMove;
int[]resultArray=新int[10000];
for(int i=0;inextInt(20)
将在0
和19
之间产生一个均匀分布的值。因此nextInt(20)-10
将产生一个介于-10
和9
之间的值。正如您所看到的,这种分布的平均值是-0.5
。执行N
这种随机选择的平均值将是-0.5N
。换句话说,随着时间的推移,您将看到总和向负值漂移,因为您使用的是相同的random函数用于X和Y坐标,该点将向左上角漂移
您应该使用nextInt(21)-10
,它将在-10
和10
之间产生一个均匀分布的值,并得到您期望的结果。nextInt(20)-10
给出一个介于-10和+9(含)之间的随机数,平均值为-0.5,即向左上方缓慢移动。要获得介于-10和+10(含)之间的数字,您需要使用nextInt(21)-10
@Andreas,哇,这太疯狂了!最大可能数字的如此小的差异导致了如此大的差异并捕获了光标!