Your method fails the distribution test if lo < 0.
However, this works:
Code: Select all
Function = Rnd*(hi-(lo>=0) - lo) - .5 + lo
That is replace +1 with '-(lo>=0)'
Using FBC's official 32-bit distribution and Mersenne Twister:
FB's Double range comes in at 101MHz. I am using badidea's loop overhead filter to get the speed. My Int approach for LongInt comes in at 34MHz. Your method comes in at 63MHz; 85% faster than my method.
Using FBC's official 64-bit distribution and Mersenne Twister.
FB's Double range comes in at 191MHz. My Int approach for LongInt comes in at 191MHz. Your method comes in at 191MHz.
I repeated the above in a different order just to make sure that I did them correctly.
So Int working with LongInt in 32-bit mode is a disaster area. Not entirely surprising.
Int working with LongInt in 64-bit mode is as fast as Double and there is no difference between your method and mine. The latter surprised me because just looking at the two methods would suggest that your code should be faster - I am using Int and you have the extra factor of '- .5'. "Int() is notoriously slow" doesn't seem to be the case when working on LongInt in 64-bit mode. Perhaps that is not entirely surprising either.
I am going to buy into your code because not everyone is 'into' 64-bit.
FB's rnd_range using LongInt could look like this:
Code: Select all
Function rnd_range Overload (first As Longint, last As Longint) As LongInt
Function = Rnd * (last - first -(first>=0)) - .5 + first
That covers [-first, -last], [-first, last] and [first, last].
If fxm is reading this he may want to include that in the Help file.
Your code is slightly less elegant than mine but it is more efficient. MrSwiss may give it a 4, or even a 5, compared to my paltry 3. No doubt he would give his code a 9 for what I see as a right 'dog's dinner'. <smile>