随机数及概率
package a;
/**
* @author 真他喵的学不动咯
* @create 2022-08-07--10:49
*/
public class randnum {//随机函数
public static void main(String[] args) {
System.out.println("***********************");
int count=0;
double ans = Math.random();//return [0,1) 等概率返回return [0,1) 的小数
int testTime=100000;
for (int i=0;i<testTime;i++){ //统计从0~testTime的次数
if (Math.random()<0.3){ //统计返回的数小于0.3的概率
count++;
}
}
System.out.println((double)count/(double)testTime); //算出Math.random()<0.3的概率,在执行testTime次的时候
System.out.println("***********************");
//[0,1) *8 [0,8) Math.Random*8
double ansone=Math.random()*8;//返回【0,8)返回的随机小数
int countone=0;
for(int i=0;i<testTime;i++){
if(Math.random()*8<4){ //在【0,8)中如果小于4,总共4段,则概率应该为0.5左右
countone++;
}
}
System.out.println((double) countone/(double)testTime);
System.out.println("***********************");
int K=9;
//如果K=9,那么(int)Math.Random返回[0~8]范围内的任何一个整数
//[0~8]范围内的任何一个整数出现是等概率的
int[] counttwo =new int[9];//设置counttwo是长度为9的int型数组
//counttwo[0]表示0出现的次数 counttwo[1]表示1出现的次数
//统计出现的次数
for (int i=0;i<testTime;i++){
int anstwo=(int)(Math.random()*K); //[0,K) 应该返回【0,K-1】的任何一个整数
counttwo[anstwo]++;//anstwo出现几,就把几的次数++
//anstwo相当于一个索引,counttwo相当于索引对应的值
}
for (int i=0;i<K;i++){ //i<K,能出现0~8范围的数
System.out.println(i+"这个数出现了"+counttwo[i]+"次");
}
System.out.println("***********************");
int countthree=0;
double x=0.7; //设x=0.7; 0~0.7
for (int i=0;i<testTime;i++){
if (x>xToPower2()){ //统计返回的数小于0.7的概率 返回的数小于0.7则countthree++
countthree++;
}
}
System.out.println("二次方为概率:"+(double)countthree/(double)testTime); //输出概率
System.out.println("y的二次方为:"+Math.pow(x,2));//用作对比比较,x^2
System.out.println("***********************");
System.out.println(Math.max(Math.random(),Math.random())); //输出为[0,1)
System.out.println("***********************");
int countfour=0;
double y=0.7; //设y=0.7; 0~0.7
for (int i=0;i<testTime;i++){
if (xToPower3()<y){ //统计返回的数小于0.7的概率 返回的数小于0.7则countthree++
countfour++;
}
}
System.out.println("三次方为概率:"+(double)countfour/(double)testTime); //输出概率
System.out.println("y的三次方为:"+Math.pow(y,3));//用作对比比较,y^3
System.out.println("***********************");
}
//方法返回【0,1)的一个小数
//任意x属于【0,1),返回的概率为x^2
//这个方法只是处理x出现的概率问题 把概率变成x^2
public static double xToPower2(){ //返回的是[0,1)的数
return Math.max(Math.random(),Math.random()); //返回两次Math.random中的最大值
//如果想获得x,只有在rand1返回x并且rand2返回x的时候,其中最大的返回数是x的时候,才能获得x
// P(x)=P(x1)*P(x2) P(x1)=x;P(x2)=x;这个时候P(x)=x^2
}
//任意x属于【0,1),返回的概率为x^3
public static double xToPower3(){ //返回的是[0,1)的数
return Math.max(Math.random(),Math.max(Math.random(),Math.random())); //返回三次Math.random中的最大值
}
}
//day2 00''56''00