Rnd. ???

Monkey Forums/Monkey Programming/Rnd. ???

Paul - Taiphoz(Posted 2012) [#1]
can anyone explain to me why i am having to do this.

Int(Rnd(1,3))-1

instead of this

int(rnd(0,1))

is it due to the way the float is being rounded up or summit, seems a bit odd to me, thought I would ask.


Gerry Quinn(Posted 2012) [#2]
I think what you want is Int( Rnd( 3 ) ).

It's the same as Int( Rnd( 0, 3 ) ).

Both should give you 0, 1 or 2 with equal probability.

If you would be more comfortable with the integer rand() function from C/C++, I wrote a Monkey clone of the MSVC version - you can find it in the code section of the forum.

I use it myself, but then again I am old skool and was taught to fear floating point numbers.


Paul - Taiphoz(Posted 2012) [#3]
The problem I was asking about is the range, I think you missed it.

Int(Rnd(1)) would be what I wanted, giving a value of either 0 or 1, but it only gave 1.

I then tried Int(Rnd(0,1)) which also only gave 0.

I then tried. Int(Rnd(1,2)) which still never gave the result I was expecting.

In the end to get either a 0 or 1, I had to do this.
Int(Rnd(1,3))-1

Which as I said, seems very very odd.


jayparker(Posted 2012) [#4]
What about Int(Rnd(2))? Gives 0 or 1.


muddy_shoes(Posted 2012) [#5]
Casting a Float to Int does not round the number to the nearest integer, it truncates towards zero. Int(Rnd(2)) would give you what you wanted.


Paul - Taiphoz(Posted 2012) [#6]
Ah so thats whats happening.