Code for generating randomized floating-point numbers

Share your advanced PureBasic knowledge/code with the community.
Axeman
User
User
Posts: 89
Joined: Mon Nov 03, 2003 5:34 am

Code for generating randomized floating-point numbers

Post by Axeman »

For some reason, PureBasic doesn't seem to come with a floating-point random number generator. The code below lets you use the integer random number generator function to create floating-point random numbers.

Code: Select all

; Code for generating randomized floating-point numbers.


; These constant declarations are required for the code below. Note that we are using the 32 bit version here as it will work for both 32 and 64 bit hardware.
#HIGH_RANDOM = 2147483646 : #LOW_RANDOM = 715827882

; ---

; This gives us a random unsigned normal value in the range 0.0 to 1.0. Make sure that the receiver is a floating-point data type, otherwise you'll get an integer value.
value.d = Random( #HIGH_RANDOM ) / #HIGH_RANDOM

; This gives us a random sign value. It will be either -1.0 or +1.0.
sign.d = ( Random( 1 ) * 2.0 ) - 1.0

; This gives us a random signed normal value in the range -1.0 to +1.0.
value.d = ( Random( #HIGH_RANDOM ) / #HIGH_RANDOM ) * ( ( Random( 1 ) * 2.0 ) - 1.0 )

; This also gives us a random signed normal value in the range -1.0 to +1.0, but it's a lot more efficient. It likely doesn't have the same degree of float precision as the previous version though, but probably enough for most purposes.
value.d = ( Random( #HIGH_RANDOM, #LOW_RANDOM ) / #LOW_RANDOM ) - 2.0

; This gives us a random signed number in the range set via 'low_number.d' and 'high_number.d'. Both the low and high numbers are inclusive. Negative inputs are allowed.
low_number.d = -2.0 ; This must be less than or equal to 'high_number.d'.
high_number.d = 2.0
value.d = ( ( high_number.d - low_number.d ) * ( Random( #HIGH_RANDOM ) / #HIGH_RANDOM ) ) + low_number.d