Dark Bit Factory & Gravity

PROGRAMMING => Freebasic => Topic started by: Clyde on May 03, 2006

Title: Using Random Numbers
Post by: Clyde on May 03, 2006
I dont suppose anyone knows what the proper way of using Rnd in FB is please folks?

In BB you'd use for example:

RandomNumber1=Rand(0,255)
RandomNumber2=Rand(64,120)


At the moment, i've been using in FB things like:

Code: [Select]
RandomNumber1=int(Rnd*255)
RandomNumber2=int(Rnd(1)*255)

But ive a shrewd suspicion, im using Rnd wrongly.

And hints and tips,
Much appreciated - Clyde


Quote
Rafryer Wrote:

Rnd will return a random value between 0.0 and 1.0 so just use:

number=Rnd*maximum

if number is an integer then the result will be 0-maximum inclusive but if it's a single then the result will be 0-(not quite maximum)

in the case of single, Rnd*255.0 will return a value between and including 0.0 and 254.9922 (not sure why it doesnt go all the way to 255)

and if you wanted a random number between 10 and 20 do something like:

number=(Rnd*10.0)+10.0

Quote

Shockwave Wrote:

And if you want your random number range to be partly negative, just subtract from the number you generated to pull it into the range you want.
Title: Re: Using Random Numbers
Post by: Blitz Amateur on May 04, 2006
I took a moment and wrote up a function ot make it so you can use Rand just as you would in BB. And for double precision floats, I made a function called FRand.

Should work great for ya =)


Code: [Select]
sub SeedRnd(byval seed as double)
    randomize seed
end sub

function Rand(ByVal lower as integer, ByVal upper as integer)
    dim temp as integer
    if upper < lower then
        temp=upper
        upper=lower
        lower=temp
    endif
    dim value as integer
    dim dist as integer
    value=lower
    dist = abs(lower-upper)
    return (rnd(1)*dist) + value
End function

function FRand(ByVal lower as double, ByVal upper as double) as double
    dim temp as double
    if upper < lower then
        temp=upper
        upper=lower
        lower=temp
    endif
    dim value as double
    dim dist as double
    value=lower
    dist = abs(lower-upper)
    return (rnd(1)*dist) + value
End function
Title: Re: Using Random Numbers
Post by: Clyde on May 04, 2006
Very handy, nice on BA :D

Cheers and all the best,
Clyde.