C#使用System.Random值进行故障排除

时间:2013-04-17 15:08:44

标签: c# random

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

2 个答案:

答案 0 :(得分:8)

看看这段代码:

 Math.Log(rand1)

那不是试图记录随机数...它试图记录一个随机数生成器的日志。你需要这样的东西:

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

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

答案 1 :(得分: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;