# VB Vectorized RNG 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 numbers from a stream.
Module VectorizedRNGExample

Sub Main()

Unlike scalar-type generators whose output is a successive random number, vector
generators produce a vector of n successive random numbers from a given
distribution. Vector type random number generators will generally perform
better than scalar ones because overhead expense of a function call
is comparable to the total time required for computation.

A stream is constructed from an optional seed, and an optional enumerated value specifying which
algorithm to use for generating random numbers uniformly distributed in the interval (0, 1).
Dim Seed As Integer = &H345
Dim Stream As New RandomNumberStream(Seed, RandomNumberStream.BasicRandGenType.MersenneTwister)

NMath provides distribution modules for many continuous and discrete distributions, each with
their own distribution parameters.
Dim mean As Double = 1.0
Dim Sigma As Double = 1.0
Dim Dist As New DoubleRandomGaussianDistribution(mean, Sigma)

You can use a stream and distribution to fill an array.
Dim N As Integer = 100
Dim Start As Integer = 0
Dim A(N) As Double
Dist.Fill(Stream, A, Start, N)

Or to fill a new vector or matrix.
Stream.Reset(Seed)
Dim V As New DoubleVector(N, Stream, Dist)

Console.WriteLine()

Display a histogram.
Dim numbins As Integer = 10
Dim Hist As New Histogram(numbins, V)
Console.WriteLine(Hist)

If you want the performance of a vectorized random number generator, but still need to access the
random deviates sequentially, NMath provides Module RandomNumbers, which uses a stream to
buffer the random numbers internally.
Dim BufferSize As Integer = 100
Dim Rnd As New RandomNumbers(Of Double, DoubleRandomGaussianDistribution)(Seed, Dist, BufferSize)

For I = 0 To 9
Console.WriteLine("Next() = {0}", CType(Rnd.Next(), Double))
Next

Console.WriteLine()
Console.WriteLine("Press Enter Key")