bmx-ng / brl.mod

BlitzMax Runtime Libraries, for BlitzMax NG.
12 stars 11 forks source link

[random.mod] Add Rand() overloads to support "float/double" too? #320

Open GWRon opened 5 months ago

GWRon commented 5 months ago

brl.random functions are from a time where "overloads" were not supported.

Wouldn't it be OK to add overloads so "Rand()" accepted double/float too? and that it returned a "float" value then?

Rand(-1.5, 1.9) would return a Float yes, but when storing it in a integer as before you will get a cast (explicitely or when having the warnings disabled). So result would there be -1, 0 or 1.

Only situation in which it is NOT working is, if someone disabled the warnings and was able to use Float where Int was requested, and THEN was storing the result in a Float. In this special situation you would see a different behaviour:

"Rand:Int(int,int)" behaviour:

Local value:Float = 100.0
value :- Rand(0, 2.5) 
'value is now 100, 99 or 98

"Rand:Float(float,float)" behaviour (assumed "overload"):

Local value:Float = 100.0
value :- Rand(0, 2.5) 
'value is now 100 - 97.5

"Rand:Float(float,float)" behaviour (assumed "overload") in case the user was aware that they use Rand for integers, and Rnd for doubles:

Local value:Int = 100
value :- Rand(0, 2.5) 
'value is now 100, 99 or 98
DruggedBunny commented 5 months ago

If it helps support the case, I ended up doing this recently!

    ' Just to tidy up Rnd Double warnings!

    Function RndF:Float (minValue:Float = 1, maxValue:Float = 0)
        Return Float (Rnd (minValue, maxValue))
    End Function
HurryStarfish commented 5 months ago
Local value:Float = 100.0
value :- Rand(0, 2.5) 
'value is now 100, 99 or 98

If such an overload was added, then any existing code that does something like this would subtly break. The next time it was compiled, it would suddenly produce different results than it used to. Adding a RndF shouldn't be an issue though. Overloads are useful to write multiple versions of a function for different parameter lists, but the important difference between Rand and Rnd is in the values they return. They don't just take different parameters, they also do different things, so I think giving them different names was the right choice. They aren't very good names, something like RandomInt and RandomDouble (and then the new one would be RandomFloat) would have been better, but these are names that came from the old BlitzBasic days...