Random float function

Just starting out? Need help? Post your questions and find answers here.
User avatar
PureLeo
Enthusiast
Enthusiast
Posts: 221
Joined: Fri Jan 29, 2010 1:05 pm
Location: Brazil

Random float function

Post 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)
User avatar
kenmo
Addict
Addict
Posts: 2033
Joined: Tue Dec 23, 2003 3:54 am

Re: Random float function

Post 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 :)
User avatar
PureLeo
Enthusiast
Enthusiast
Posts: 221
Joined: Fri Jan 29, 2010 1:05 pm
Location: Brazil

Re: Random float function

Post by PureLeo »

Thanks a lot. It was being a pain to think of something like that :)
Post Reply