News:

Masm32 SDK description, downloads and other helpful links
Message to All Guests
NB: Posting URL's See here: Posted URL Change

Main Menu

Skewed random numbers

Started by jj2007, August 26, 2017, 01:17:10 PM

Previous topic - Next topic

jj2007

Imagine you have a table of probabilities in the data section:
pTable dd 25, 55, 15, 3, 2, 0 ; zero-delimited table holds the relative probabilities

For illustrative purposes, the sum is 100 in this case, but it could be any combination of frequencies.

Goal is to obtain random numbers that are distributed according to this table's frequencies, for example:2499
5501
1499
300
199


The source:

include \Masm32\MasmBasic\Res\JBasic.inc        ; download

.data
pTable  dd 25, 55, 15, 3, 2, 0  ; zero-delimited table holds the relative probabilities
pCount  dd 6 dup(?)             ; result counter

  Init
  PrintLine Chr$("This code was assembled with ", @AsmUsed$(1), " in ", jbit$, "-bit format")
  Rand(pt:offset pTable)        ; probability table: pointer

        xor ebx, ebx
@@:     void Rand(pt)           ; void because Rand(pt) returns eax (we need rax)
        lea rdi, pCount
        inc dword ptr [rdi+4*rax]       ; eax will be in the range 0...4
        inc ebx
        cmp ebx, 9999999
        jb @B

        xor ebx, ebx
@@:     lea rdi, pCount
        Print Str$("%i\n", dword ptr [rdi+4*rbx])       ; display the results
        inc rbx
        cmp rbx, 5
        jb @B
EndOfCode


Output:This code was assembled with ml64 in 64-bit format
2499469
5501160
1499102
300666
199602


Project attached - it works also with ordinary 32-bit MB ;)