Random Generator


#1

Hello,
I was attempting to create a random color every time I shook my iPhone and I noticed the following code would always return 0.0000…
r = random() % 256/256;
g = random() % 256/256;
b = random() % 256/256;
NSLog(@"===shake started: random: r:%f, g:%f, b:%f",r,g,b);

However in order to get the values ranging between 0.0 and 1.0 which is what I wanted to generate the random rgb values I had to typecast the 256 like so:
r = random() % 256/(float)256;
g = random() % 256/(float)256;
b = random() % 256/(float)256;

Did anyone else experience this or am I the only one?

Thanks!


#2

Random() % 256 gives you an integer from 0 to 255. For purposes of this discussion, the value doesn’t matter, only that it is an integer so let’s just say it is 120 and the equation then looks like:

r = 120 / 256;

Within integer math, we don’t get fractions of numbers. Therefore, this equation is actually equal to 0. (256 / 256 = 1, 257/256 = 1) Even though the variable we are putting it into is a float, the expression evaluates without that information.

The result of the division must be a float before we assign its value to a variable. If one or both of the operands in an equation are floating point numbers, the result evaluates to a floating point number. You can tell the compiler that a variable/literal is a float by casting it, like you’ve done here. But, you can also tell the compiler that a value is a float (technically, a double) by suffixing .0 to it.

In the text, these equations actually read as r = random() % 256 / 256.0; which is interpreted by the compiler differently than a simple 256. (Also, if you really want a float and not a double, you can do 256.0f)