【发布时间】:2013-04-10 10:22:19
【问题描述】:
我正在尝试创建随机数,然后使用我发现的这个 box muller 算法。我遇到的问题是使用 System.Random 值进行任何类型的数学运算。我不能取平方根、对数或将它们与浮点值混合。这是我的随机分布代码。想了几天也没想到什么。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Random rand1 = new Random();
Console.WriteLine("999 Doubles1.");
for (int ctr = 0; ctr <= 999; ctr++)
Console.Write("{0,8:N3}", rand1.NextDouble());
Console.WriteLine();
Random rand2 = new Random();
Console.WriteLine("999 Doubles2.");
for (int ctr = 0; ctr <= 999; ctr++)
Console.Write("{0,8:N3}", rand2.NextDouble());
Console.WriteLine();
float mu = .75F;
float sigma = .1F;
float z1 = Math.Sqrt(-2 * Math.Log(rand1)) * Math.Sin(2 * Math.PI * rand2);
float z2 = Math.Sqrt(-2 * Math.Log(rand1)) * Math.Cos(2 * Math.PI * rand2);
float x1 = mu + z1 * sigma;
float x2 = mu + z2 * sigma;
}
}
}
【问题讨论】:
-
您不能取负数的平方根(除非您使用复数)。此外,您不能使用随机对象传递给需要数字的函数!
-
您正在创建两个
Random实例,这是个坏主意。创建一个实例,多次调用NextDouble() -
-1:没有引用编译器错误消息,让您更难看到您最觉得卡在什么地方。