Page 1 of 1

Random float function

Posted: Thu Mar 03, 2011 2:21 am
by PureLeo
Hi.

I've been looking for a good pseudo random function for floating numbers with range (min and max), and I've found this on a PHP code website...

Code: Select all

Procedure.f randf(min.f,max.f)
    ProcedureReturn (min+ValF("0."+Str(Random(999)))*(Abs(max-min)));
EndProcedure
I can't say it doesn't "work", but well...

Does anyone have a good algorythm for that?

(I've been searching in the forums and have found some functions for that but none with min and max parameters)

Re: Random float function

Posted: Thu Mar 03, 2011 2:27 am
by kenmo
Ah, no need for string conversions! Try something like this:

Code: Select all

Procedure.f RandF(Min.f, Max.f, Resolution.i = 10000)
  ProcedureReturn (Min + (Max - Min) * Random(Resolution) / Resolution)
EndProcedure

Debug "Procedure:"
For i = 1 To 10
  Debug StrF(RandF(10.0, 20.0), 2)
Next i
Debug ""

Macro MacRandF(Min, Max, Resolution = 10000)
  ((Min) + ((Max) - (Min)) * Random(Resolution) / (Resolution))
EndMacro

Debug "Macro:"
For i = 1 To 10
  Debug StrF(MacRandF(10.0, 20.0), 2)
Next i
Debug ""
Two versions, same thing. I just like using macros where possible :)

Re: Random float function

Posted: Thu Mar 03, 2011 6:11 am
by PureLeo
Thanks a lot. It was being a pain to think of something like that :)