# Floats and integers

Hi,

I’m a bit confused on how numbers are handled in squirrel. To illustrate this I want to generate a random number between 0 and 255

math.rand() gives a number between 0 and RAND_MAX, so in order to get a float between 0 and 1 i tried to do this:

math.rand()/RAND_MAX

This however always returned 0! #-o

So I took a step back and tried
server.log(4/5); This returns 0 again. WTF?

Ok, next attempt
server.log(4.0/5.0); this returne 0.8, much better.

But back to my original issue, I tried this, and it seems to finally give me the right numbers, but I’m pretty sure this can’t be the most simple way to do this.
server.log( math.rand()*1.0 / RAND_MAX*1.0 * 255);

So, what is it that I’m missing?
Thanks

The rule in Squirrel is the same as the rule in C: if both sides of the “/” are integers, the result is the rounded-down integer – otherwise it’s a float. The same is true for the other arithmetic operators such as “*”. So
(math.rand()*256.0) / (RAND_MAX+1)
is probably the simplest way to do it. To make all 256 numbers 0-255 equally likely when rounded down to an integer again, the result needs to range from 0.0 to 255.9999…, not from 0.0 to 255.0.

Peter

Interesting, I didn’t know that this was the rule. It’s also a bit confusing to have these strict rules in a language that’s not really strictly typed.
Thanks for the clarification.

On looking at it a bit more, the fact that it’s RAND_MAX (and PI), rather than math.RAND_MAX and math.PI, was unintended. But it’s too late to change now.

Peter

Sorry to open this one up again - @peter, @richinminerals how do you actually set the lower values for the random number?