Created
March 29, 2012 15:08
-
-
Save majiang/2238327 to your computer and use it in GitHub Desktop.
Mersenne Twister
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
' VB translation of http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/C-LANG/mt19937-64.c | |
Public Class MT | |
Private Const NN = 312 | |
Private Const MM = 156 | |
Private Const MATRIX_A = &HB5026F5AA96619E9UL | |
Private Const UM = &HFFFFFFFF80000000UL | |
Private Const LM = &H7FFFFFFFUL | |
Private mt(NN - 1) As ULong | |
Private mti As Integer = NN + 1 | |
Private Function sumup(ByVal ParamArray a() As ULong) As ULong | |
sumup = 0UL | |
For Each e As ULong In a | |
If e = 0 Then Continue For | |
Dim n As ULong = 1UL + Not e | |
If sumup < n Then | |
sumup += e | |
Else | |
sumup -= n | |
End If | |
Next | |
End Function | |
Private Function mul(ByVal a As ULong, ByVal b As ULong) As ULong | |
Const low As ULong = (1UL << 32) - 1 | |
Dim al As ULong = a And low | |
Dim bl As ULong = b And low | |
Dim p As ULong = (a >> 32) * bl << 32 | |
Dim q As ULong = (b >> 32) * al << 32 | |
Return sumup(p, q, al * bl) | |
End Function | |
Public Sub init_seed(ByVal seed As ULong) | |
mti = 0 | |
mt(mti) = seed | |
While True | |
Dim prev = mt(mti) | |
mti += 1 | |
If NN <= mti Then Exit Sub | |
mt(mti) = sumup(mti, mul(&H5851F42D4C957F2DUL, (prev Xor (prev >> 62)))) | |
End While | |
End Sub | |
Private Sub gen() | |
Dim x As ULong | |
If mti > NN Then init_seed(&H1571UL) | |
Dim mag01() As ULong = {0UL, MATRIX_A} | |
For i As Integer = 0 To NN - MM - 1 | |
x = (mt(i) And UM) Or (mt(i + 1) And LM) | |
mt(i) = mt(i + MM) Xor (x >> 1) Xor mag01(x And 1UL) | |
Next | |
For i As Integer = NN - MM To NN - 2 | |
x = (mt(i) And UM) Or (mt(i + 1) And LM) | |
mt(i) = mt(i + MM - NN) Xor (x >> 1) Xor mag01(x And 1UL) | |
Next | |
x = (mt(NN - 1) And UM) Or (mt(0) And LM) | |
mt(NN - 1) = mt(MM - 1) Xor (x >> 1) Xor mag01(x And 1UL) | |
mti = 0 | |
End Sub | |
Public Function UL() As ULong | |
If NN <= mti Then gen() | |
UL = mt(mti) | |
mti += 1 | |
UL = UL Xor UL >> 29 And &H5555555555555555UL | |
UL = UL Xor UL << 17 And &H71D67FFFEDA60000UL | |
UL = UL Xor UL << 37 And &HFFF7EEE000000000UL | |
UL = UL Xor UL >> 43 | |
End Function | |
End Class |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment