-8

我正在尝试创建随机数,然后使用我找到的这个 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;
        }
    }
}
4

2 回答 2

8

看看这段代码:

 Math.Log(rand1)

这不是试图获取随机数的日志......它试图获取随机数生成器的日志。你需要类似的东西:

double randomNumber = rand1.NextDouble();
// Code using Math.Log(randomNumber)

对随机数生成器本身执行数值运算的概念没有多大意义。

于 2013-04-17T15:11:51.743 回答
2

用这个:

            double double1 = rand1.NextDouble();
            double double2 = rand1.NextDouble();

            double z1 = Math.Sqrt(-2 * Math.Log(double1)) * Math.Sin(2 * Math.PI * double2);
            double z2 = Math.Sqrt(-2 * Math.Log(double1)) * Math.Cos(2 * Math.PI * double2);
            double x1 = mu + z1 * sigma;
            double x2 = mu + z2 * sigma;
于 2013-04-17T15:15:39.240 回答