GLBasic forum
Main forum => GLBasic  en => Topic started by: spicypixel on 2015Nov06

This is a pseudorandomnumbergenerator which I'd really like to test out in GLB. My math knowledge is poor so thought I'd post this little function to see if anyone can answer my question regarding converting it to GLB. It's just the math section that needs doing really the results can be DEBUG output rather than printed (as per the example).
//by default these are 0
global BSDState
global MSState
for i = 1 to 10
print randBSD()
next
for i = 1 to 10
print randMS()
next
function randBSD:
randBSD = (1103515245 * BSDState + 12345) mod (2 ^ 31)
BSDState = randBSD
endfunction
function randMS:
MSState = (214013 * MSState + 2531011) mod (2 ^ 31)
randMS = integer(MSState / 2 ^ 16)
endfunction

Not tested but...
GLOBAL BSDState#
GLOBAL MSState%
FUNCTION randBSD#:
BSDState = MOD( (1103515245 * BSDState + 12345), POW (2, 31) )
RETURN BSDState
ENDFUNCTION
FUNCTION randMS%:
MSState% = MOD ( (214013 * MSState + 2531011), POW (2, 31) ) / POW(2, 16)
RETURN MSState%
ENDFUNCTION
BTW POW(x,y) can be replaced by the POW(x,y) result. eg. POW (2, 16) could be replaced with 65536, maybe a compiler optimisation does this anyway?

Good idea about the value of the POW to optimise calculations. I pretty much did what you have done there in my efforts by putting the MOD at the start, I think my only problem was not defining float or integer in the function name (I guess). Will test now my good friend. I believe the BSD pnrg is poor in comparison to the Microsoft method.
Results to be posted shortly :)

The BSD formula just blatantly didn't work and alternated between 0 and 12345. The MS routine gave good PRNGs but needs some sort of seeding as the sequence was identical each time. It was good to see the generation of random numbers from a small algo though :)

I'm not sure how fast the MOD or the POW commands are, may not be so good for time critical sections of a game.

Im not sure about POW, but MOD should be no problem at all, its often included in CPU hardware.

I replaced the POW's with integers and all was fine :)

POW is normally for float numbers. better use ASL(1,n) than POW(2,n).
The hex notatation 0x.... becomes easy with 2^n numbers: 2^4 = 0x10 2^8 = 0x100 2^12=1000
In the windos' accessories, the calculator has a decimal to/from hex converter, in the dev' mode.

I would expect any halfdecent compiler to do optimizations like this automatically (at least when you turn on optimizations, you should do so in GLBasic too!).