VB Random Number Example

← All NMath Code Examples


Imports System

Imports CenterSpace.NMath.Core

Namespace CenterSpace.NMath.Examples.VisualBasic

  A .NET example in Visual Basic showing how to generate random number from a normal distribution,
  using the class RandGenNormal, and place them in a histogram.
  Module NormalRNGExample

    Sub Main()


      Dim Mean As Double = 70.0
      Dim Variance As Double = 10.0

      Create a default generator. The default generator will generate 
      random numbers from a normal distribution with a specified mean
      and variance.
      Dim NormalRng As New RandGenNormal(Mean, Variance)

      Now construct a vector of random numbers using this generator.
      Dim NumRandDeviates As Integer = 200
      Dim RandomVec As New DoubleVector(NumRandDeviates, NormalRng)

      Create a histogram with equal sized bins for the random numbers.
      Dim NumBins As Integer = 20
      Dim H As New Histogram(NumBins, RandomVec)


      Print out the histogram in a "stem leaf" format.
      Console.Write(NumRandDeviates.ToString() + " random deviates from a normal(")
      Console.Write(Mean.ToString() + "," + Variance.ToString())
      Console.WriteLine(") distribution:")

      Change the mean and variance for generator and check the mean and  
      variance of the generated deviates.
      NormalRng.Mean = -2.0
      NormalRng.Variance = 1.0
      RandomVec = New DoubleVector(1000, NormalRng)

      Dim MeanOfDeviates As Double = NMathFunctions.Mean(RandomVec)
      Console.Write("Distribution mean = " + NormalRng.Mean.ToString() + ",")
      Console.WriteLine("mean of deviates = " + MeanOfDeviates.ToString())

      Dim VarianceOfDeviates As Double = NMathFunctions.Variance(RandomVec)
      Console.Write("Distribution variance = " + NormalRng.Variance.ToString())
      Console.WriteLine(", variance of deviates = " + VarianceOfDeviates.ToString())

      Replace the vectors contents with new random numbers
      RandomVec.Transform(New Func(Of Double)(AddressOf NormalRng.NextDouble))

      Console.WriteLine("Press Enter Key")

    End Sub
  End Module
End Namespace

← All NMath Code Examples