"Native" random/rand

Just starting out? Need help? Post your questions and find answers here.
xakep
User
User
Posts: 40
Joined: Fri Mar 25, 2016 2:02 pm
Location: Europe

"Native" random/rand

Post 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.
wilbert
PureBasic Expert
PureBasic Expert
Posts: 3870
Joined: Sun Aug 08, 2004 5:21 am
Location: Netherlands

Re: "Native" random/rand

Post by wilbert »

The problem is that your variables are signed variables and that the PB shift right operator performs an arithmetic shift.
Windows (x64)
Raspberry Pi OS (Arm64)
Post Reply