Random Floats using built-in PRNG

Posted by on June 13, 2009

Random floats are kind of a mystical thing in PB, however it can be achieved to a certain degree without having to stack calls on a per decimal fashion.

Here is a simple implementation that will get you going, this is meant specifically for games but it could find other uses…

Macro RandomF() ; returns a random float from 0.0 to 1.0
	( Random(64325) * 0.00001555 )
EndMacro
Macro RandomFC() ; returns a random float from -1.0 to 1.0
	( 2.0 * ( RandomF() - 0.5 ) )
EndMacro

Try it out yourself, if you need a wider range of numbers just multiply the result by a certain factor. I use this and other similar macros for most of my float random needs in PB. Should you need to stack the calls, just make procedures out of the macros.

Similar routines are found inside the Quake3 sources if you care to read them (hint: if you look carefuly there is a comment line inside the game source that reads “// What the fuck?” — Just priceless, seriously).

Cheers.

2 Comments on Random Floats using built-in PRNG

Closed

  1. tron86 says:

    Thanks for this! I was doing it the wrong way clearly xD

    Macro RandomFloat( minimum, maximum )
    	(( minimum + Random(maximum-minimum) )*1) + (( minimum + Random(maximum-minimum) )*0.1) + (( minimum + Random(maximum-minimum) )*0.01)
    EndMacro
    
    Debug RandomFloat( 5, 10 )
    • admin says:

      Yeah that’s hardly the way to do it, plus you’re limiting yourself to only 2 decimals and you’re not only calling Random() three times but you’re also performing redundant subtractions and whatnot… I’ve seen this in the official forums and I almost laughed at it. Just don’t do it, it’s bad programming. We already use macros due to lack of inlining… Don’t make it worse!.