random numbers drawn from a normal distribution
BlitzMax Forums/BlitzMax Beginners Area/random numbers drawn from a normal distribution
| ||
I am trying to create a function which will give me random numbers which are drawn from a normal (i.e. Gaussian) distribution - in which I can input the mean and standard deviation as arguments. (I know that there is a 'quick and dirty' way of getting 'normalish' random distributions by just adding several random numbers together but I wanted something a bit more precise). I managed to find some code in Pascal which I converted to Blitzmax but the output I get is rather odd.... for 10 iterations - I got this as output - I'm not even sure what these symbols mean -1.#I -1.#I -1.#I -1.#I -1.#I -1.#I -1.#I -1.#I -1.#I -1.#I Can anybody help me spot the error in my function or at least tell me why I get this strange non-numeric output? Many thanks in advance... Here is my code..... Strict SeedRnd MilliSecs() Local rNum:Float For Local i:Int = 1 To 10 rNum= randomgaussian(0,1) DrawText rNum,400,10+(i*30) Print dectostring(rNum,2) Next End Function RandomGaussian:Float(mean:Float,SD:Float) Local U1:Float, S2:Float, rGauss:Float Repeat U1= 2*Rnd() - 1 S2= Sqr(U1) + Sqr(2*Rnd()-1) Until S2 < 1 rGauss= Sqr(-2*Log(S2)/S2) * U1 * SD + Mean Return rGauss EndFunction Function DecToString:String(value:Double,places:Int=5) Return Left(String(value),Instr(String(value),".") + places) EndFunction |
| ||
Function RandomGaussian:Float(mean:Float,SD:Float) Local U1:Float, U2:Float, M:Float, S2:Float, rGauss:Float Repeat U1= Rnd(-1,1) U2 = Rnd(-1,1) S2= U1*U1 + U2*U2 Until S2 < 1 M = Sqr( -2*Log(S2)/S2 ) rGauss= M * U1 * SD + Mean ' NOTE: You get a second, independent, value essentially for free with M * U2 * SD + Mean Return rGauss EndFunction Box-Muller also generates two values. Just remember that BlitzMax uses degrees. So something like Cos( 2*Pi*U ) should be Cos( 360*U ) Both methods rely on generating a random "direction", meaning a randomly oriented unit vector. |
| ||
Many thanks indeed - works great! |