生成0~100之间的随机数
import java.util.Random;
public class RandomNum {
public static void main(String[] args)
{
int i,j;
Random r =new java.util.Random(10);
for(j=0;j<10;j++)
{
for(i=0;i<10;i++)
{
System.out.printf("%3d ", r.nextInt(100));
}
System.out.print("\n");
}
}
}
生成[0,1]之间均匀分布的随机数
public class RandomNum {
static double rand01(double[] r)
{
double base,u,v,p,t1,t2,t3;
base=256.0;
u=17.0;
v=139.0;
t1=u*(r[0])+v;
t2=(int)(t1/base);
t3=t1-t2*base;
r[0]=t3;
p=r[0]/base;
return p;
}
public static void main(String[] args)
{
int i;
double[] r= {5.0};
for(i=0;i<10;i++)
{
System.out.printf("%10.5f\n", rand01(r));
}
System.out.print("\n");
}
}
产生任意范围的随机数(范围:[m,n])
public class RandomNum {
static double rand01(double[] r)
{
double base,u,v,p,t1,t2,t3;
base=256.0;
u=17.0;
v=139.0;
t1=u*(r[0])+v;
t2=(int)(t1/base);
t3=t1-t2*base;
r[0]=t3;
p=r[0]/base;
return p;
}
public static void main(String[] args)
{
int i;
double m,n;
m=10.0;
n=20.0;
double[] r= {5.0};
for(i=0;i<10;i++)
{
System.out.printf("%10.5f\n", m+(n-m)*rand01(r));
}
System.out.print("\n");
}
}
[m,n]之间均匀分布的随机整数算法
public class RandomNum {
static double rand01(double[] r)
{
double base,u,v,p,t1,t2,t3;
base=256.0;
u=17.0;
v=139.0;
t1=u*(r[0])+v;
t2=(int)(t1/base);
t3=t1-t2*base;
r[0]=t3;
p=r[0]/base;
return p;
}
public static void main(String[] args)
{
int i,m,n;
m=100;
n=200;
double[] r= {5.0};
for(i=0;i<10;i++)
{
System.out.printf("%d\n", m+(int)((n-m)*rand01(r)));
}
System.out.print("\n");
}
}
正态分布的随机数生成
public class RandomNum {
static double rand01(double[] r)
{
double base,u,v,p,t1,t2,t3;
base=256.0;
u=17.0;
v=139.0;
t1=u*(r[0])+v;
t2=(int)(t1/base);
t3=t1-t2*base;
r[0]=t3;
p=r[0]/base;
return p;
}
static double randZT(double u,double t,double[] r) {
int i;
double total=0.0;
double result;
for(i=0;i<12;i++)
{
total+=rand01(r);
}
result=u+t*(total-6.0);
return result;
}
public static void main(String[] args)
{
int i;
double u=2.0;
double t=3.5;
double[] r= {5.0};
for(i=0;i<10;i++)
{
System.out.printf("%10.5f\n", randZT(u,t,r));
}
System.out.print("\n");
}
}
网友评论