为何我单步运行的时候每次出现的数字不一样,一旦用for循环输出的数字都是一样的了,包括用数组输出的时候也是一样的结果,请大家帮助!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using rocktest;
using System.Collections;
namespace rocktest
{
class programm
{
public static int PoissonRandomNumber(double Lemda)
{
double u;
int Z = 0;
double L;
double p = 1.0;
L = Math.Exp(-Lemda);
Random rand = new Random(); do
{
Z = Z + 1;
u = rand.NextDouble();
p = p * u; }
while (p >= L);
return Z - 1;
}
static void Main(string[] args)
{
//for (int i = 0; i < 10; i++)
Console.WriteLine(rocktest.Program.BinomialRandom(0.5, 10)); }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using rocktest;
using System.Collections;
namespace rocktest
{
class programm
{
public static int PoissonRandomNumber(double Lemda)
{
double u;
int Z = 0;
double L;
double p = 1.0;
L = Math.Exp(-Lemda);
Random rand = new Random(); do
{
Z = Z + 1;
u = rand.NextDouble();
p = p * u; }
while (p >= L);
return Z - 1;
}
static void Main(string[] args)
{
//for (int i = 0; i < 10; i++)
Console.WriteLine(rocktest.Program.BinomialRandom(0.5, 10)); }
}
}
Random rand = new Random((int)DateTime.Now.Ticks);
这一句放到方法外面。。
这个放在外面,你是静态函数,改rand为静态变量
//for (int i = 0; i < 10; i++)
Console.WriteLine(rocktest.Program.BinomialRandom(0.5, 10));
始终调用的是一个固定的随机函数,所以,输出值一样。而单步,Random rand = new Random(); 多次执行,每一次分配的内存区域都不一样。就是RANDOM函数真正发生了变化。
所以Console.WriteLine(rocktest.Program.BinomialRandom(0.5, 10)); 值就会不一样。
for (int index = 0; index < 1000;index++ )
{
Random r = new Random((int)DateTime.Now.Ticks);
Thread.Sleep(1);
Console.WriteLine(r.NextDouble());
}
可以这样写,加个Sleep
for (int index = 0; index < 1000;index++ )
{
Random r = new Random((int)DateTime.Now.Ticks);
Thread.Sleep(1);
Console.WriteLine(r.NextDouble());
}
使用Thread.Sllep(1);会影响效率么?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using rocktest;
using System.Collections;
namespace rocktest
{
class programm
{
static Random rand = new Random();
public static int PoissonRandomNumber(double Lemda)
{
double u;
int Z = 0;
double L;
double p = 1.0;
L = Math.Exp(-Lemda); do
{
Z = Z + 1;
u = rand.NextDouble();
p = p * u; }
while (p >= L);
return Z - 1;
}
static void Main(string[] args)
{
//for (int i = 0; i < 10; i++)
Console.WriteLine(rocktest.Program.BinomialRandom(0.5, 10)); }
}
}
种子值相同,生成的随机数也是相同的,不设置种子时,以当前时间作为种子,
你将for循环的次数设置到足够大,在不单步的情况下执行,
再看执行结果,你知道怎么回事了
只是 Random rand = new Random(); new这个类的时候默认用了当前系统时间作为种子,事实上,除了这个种子,电脑也产生不了什么真正的随机种子,你也不可能做个随机数生成器,比这个还要好的东西的。楼主的问题是在循环里生成了若干个Random类,这些类都是几乎同时new出来的,种子相同,所以从来都数据也相同,而你的需求根本不需要这么多Random类,有一个Random就够了,用这个Random的NextDouble方法就可以产生出一系列的随机数了。明白没?