Brl.Random bug or expected behaviour?

BlitzMax Forums/BlitzMax Programming/Brl.Random bug or expected behaviour?

Difference(Posted 2011) [#1]
This code prints 0 and 1

Shouldn't it print only zeros?
It certainly produced an non obvious error in my code, because I was doing this:

Local newindex:Int = Rand(myarray.length-1)


(Bah.Random behaves in the same way)

SuperStrict

While Not KeyHit(KEY_ESCAPE)
	Print Rand(0)
	Delay 10
Wend



GfK(Posted 2011) [#2]
In this case (and many others I've found), Blitmax cannot differentiate between 0 and Null - it treats them as the same even though they aren't.

So by using Rand(0), it treats it as if you haven't entered a value, and uses the default of 1.


Oddball(Posted 2011) [#3]
The docs say
Rand(x) Random integer in the range 1 to x (inclusive)
If x=0 the results will be in the range 1 to 0 (inclusive). Is this not what you are getting?

Last edited 2011


Difference(Posted 2011) [#4]
Thanks Gfk and Oddball, reading the docs, I see
Rand:Int( min_value:Int, max_value:Int = 1 )

I guess I've always always thought of it as an overloaded function, but of cause BlitzMax dodn't have those.

Local newindex:Int = Rand(0,myarray.length-1)
solves my issue.

I still think it's a slightly strange behavior , also since

Rnd:Double( min_value!=1,max_value!=0 )
behaves differently.


Floyd(Posted 2011) [#5]
It's typical behavior for floating point random numbers to include one endpoint while integers include both.

In mathematical notation the interval [3,4) denotes all numbers from 3 to 4, with the 3 included but the 4 excluded. Notice that such intervals combine as:

[3,4) plus [4,5) is the interval [3,5).

Nothing is counted twice ( the smaller intevals are disjoint ) and nothing is missed when they are united to form [3,5).

That would be impossible if both endpoints were included. It would certainly look more natural and symmetrical to include both, but it just doesn't work when building larger intervals from smaller ones. These considerations don't apply to integers so they can be done the way you would expect, with both endpoints included.


Difference(Posted 2011) [#6]
Thanks to Floyd for explaining the reason for this behavior in detail.