-
Math.random();
double ans=Math.random()//随机返回[0,1)之间小数
double ans2=Math.random()*8//随机返回[0,8)之间小数
int ans3=int(Math.random()*k)//[0,k-1]随机整数
//以上方法[0,x)x出现的概率都是x
//把数出现概率由x调整为x平方
return Math.max(Math.random(),Math.randomn())
-
题目:有一个能随机返回1-5随机数的函数改,得到1-7的随机数
-
首先明确目标函数和条件函数
-
通过条件函数得到0.1发生器:得到1,2返回0;得到4,5返回1;得到3重新生成
-
如何通过0,1生成函数得到目标函数:使用三个0,1生成函数(二进制位:000-111),得到0-7
-
改成0-6再+1
-
public class test1 {
//设计一个返回1-5随机数的函数
public static int f1(){
return (int)(Math.random()*5)+1;
}
//返回随机数0和1【注意不是0-1,所以不能直接得到1-7】
public static int f2(){
int i ;
do{
i=f1();
}while(i==3);
if(i<3){
return 0;
}else {
return 1;
}
}
//返回随机数0-7
public static int f3(){
return (f2()<<2)+(f2()<<1)+(f2()<<0);
}
//返回随机数0-6
public static int f4(){
int a;
do{
a=f3();
}while (a==7);
return a;
}
//返回随机数1-7
public static int f5(){
int b=f4()+1;
return b;
}
public static void main(String[] args) {
int[]count=new int[8];
int tem=0;
for (int i = 0; i < 1000; i++) {
tem=f5();
count[tem]++;
}
for (int i = 0; i < 8; i++) {
System.out.println(count[i]);
}
}
}
-
题目:从0,1不等概率到0,1等概率
-
两次结果为0,1和1,0时可以保证等概率
-
//f1有0.84的概率返回0,0.16概率返回1
public static int f1(){
return Math.random()<0.84?0:1;
}
public static int f2(){
int a=0;
do{
a=f1();
}while(a==f1());
//保证两次f1结果不同,为0/1或1/0
return a;
}