如何确保在模拟中使用唯一的随机数?

时间:2018-06-15 14:58:03

标签: vb.net random

我遇到了一个问题,我在模拟中遇到重复的随机数我写作。这是因为快速创建Random的新实例足以使用相同的种子。根据我的发现,正确的方法是使用Random的单个实例,但我不太确定如何执行此操作。

问题是我想在模拟过程中创建具有随机初始属性的许多对象,让它们从不同的分布中随机抽样,并为每次模拟复制重置对象。根据我对VBA的经验,我只需要调用Rnd()或引用全局/公共对象;但是,这些选项在这里似乎不可行或不合适。我不确定如何将多个不同类的许多实例都引用到Random的单个实例。

我的代码看起来大部分都是这样的(尽管如果真的有必要,我可以发布更完整的代码):

Sub RunSim()

    Dim Unit() as SimClass
    Redim Unit(NumberOfObjects)

    For n = 1 To Replications

        For i = 0 To NumberOfObjects
            Unit(i) = New SimClass
        Next

        For j = 1 to ProcessSteps
            For i = 0 To NumberOfObjects
                Unit(i).Process(Dist(j),P1(j),P2(j)) 'These are dist/parameter arrays
            Next
        Next

        Combine(Unit(i), NumberOfObjects)   'This condenses my objects to unit(0), part of my simulated system

        File.Write(Unit(0).GetAtts)     'This combines/returns Unit(0)'s attributes

    Next

End Sub

Public Class SimClass

    Private x, y, z, Parameter1, Parameter2 As Double
    Private avg As Double = 50
    Private std As Double = 5
    Private Dist As String

    Public Sub New
        SetX()
        SetY()
        SetZ()
        SetDist()
    End Sub

    Public Sub SetX()
        Dim Var as new Variate(Dist, avg, std)
        Me.x = Var.Draw
    End Sub

    'y, z, setters are similar

    Public Sub Process(Name, P1, P2)

        Dim Var as New Variate(Dist, Parameter1, Parameter2)

        Me.x = Me.x * Var.Draw
        'etc. y and z

    End Sub

End Class

Public Class Variate

    Private P1,P2 As Double
    Private Dist As String
    Private Rnd As New Random

    Public Sub New(Name As String, Par1 as Double, Par2 As Double)

        Dist = Name
        P1 = Par1
        P2 = Par2

    End Sub

    Public Function Draw

        Select Case Me.Dist.ToUppeer
            Case "NORM"
                Draw = NormalRV(P1, P2)
            Case Else
                'etc
            End Select

    End Function

    Private Function NormalRV()

        'Return random sample from a normal distribution with given parameters
        'Relies on Rnd.NextDouble()

    End Function

我还在RunSim()的其他地方使用Random。在整个模拟过程中是否有一种简单的方法可以插入非重复随机数?我已经看到了一些类似的问题,但大多数似乎都专注于改组数据或者不是VB.NET

1 个答案:

答案 0 :(得分:0)

首先,将Shared放在随机变量上,这样每次创建类时都不会对其进行实例化。

如果你想在其他地方重复使用它,你应该创建一个包含公共礼仪的模块,返回随机对象和/或值(google the term:singleton)