Page 1 of 1

"Native" random/rand

Posted: Fri Sep 22, 2017 3:40 pm
by xakep
Based on this article: http://www.dreamincode.net/forums/topic ... ation-102/

Partially Converted:

Code: Select all

EnableExplicit

ImportC ""
  time(*tloc = #Null)
EndImport

Global iSeed.l

Procedure.l nextNumber()
  Define iOutput.l, iTemp.l, i.i, Time.SYSTEMTIME
  
  iSeed = time()
  
  While i < 16
    i+1
    iSeed = (3039177861 * iSeed + 1)
		iTemp = iSeed >> 30
		iOutput = iOutput << 2
		iOutput = iOutput + iTemp
  Wend
  
  ProcedureReturn iOutput
EndProcedure

Procedure.d nextDouble()
  ProcedureReturn nextNumber() / $FFFFFFFF
EndProcedure

Procedure.i inRange(iMin.i, iMax.i)
  Define Diff.i
  
  Diff = iMax - iMin + 1
  ProcedureReturn (nextDouble() * Diff) + iMin
EndProcedure
My converted code seems to have some problems:

Code: Select all

Debug inRange(2, 4)
Sometime returns 1. witch is not in the range of 2 -4

Code: Select all

inRange(1, 80)
Sometime returns 0 or negative values, like -13.

Not sure why this happens, and my cpp/math knowledge is very basic.

Why all these troubles?
"Most PRNGs used in programming languages use an LCG so you might as well just use rand() to generate your random data. However, maybe you are just interested in how these things work. Maybe you don’t trust the programmers who wrote that library. Maybe you are just a plane old-fashioned do-it-yourselfer."

Sorry for my english and thanks for your time.

Re: "Native" random/rand

Posted: Fri Sep 22, 2017 3:51 pm
by wilbert
The problem is that your variables are signed variables and that the PB shift right operator performs an arithmetic shift.