# Random number generation

Hi forum,

According to the documentation

``````float ofRandom(float val0, float val1)
``````

generates random number between two values val0 and val1. Are inclusive or exclusive ?

The following snippet

``````v1 = rand() % 100;
``````

generates a random value between 0 and 99

How create the same scenario with ofRandom(…) ?

1 Like

You can’t really talk about inclusive randomness with a floating point RNG. you’ll pretty much never get exactly 0 or exactly 100 out of it because it is a floating point, you might get 0.03431 or 99.98234, but the likelyhood of getting a whole number is close to 0%.

there is a function named `ofRandomf()` for same pupose

Sorry , i did not formulated the question well enough.

I want to get integer random number instead of a float. Is there anything in OF?

you can typecast as `(int)ofRandom(-1,100)` to get integer values

1 Like

if you want to get 100 random numbers then the correct way is to start from 0, not -1 (I respectfully disagree @samdraz.).
So the way to do it is to say:
int randomNumber = (int) ofRandom(0,100);
The above will ONLY generate numbers between 0 and 99 inclusive. In other words: 0,1,2,3…99.
marinero

2 Likes

I’m a bit confused, will this NEVER generate 100 or will it have a very low chance of generating 100?

What I’m seeing is that sometimes (maybe once in a few million rolls) it ends up right at the maximum value.

I’m using ofRandom(25) for what it’s worth, I remember reading the grains of fractions extend as you get away from 0 on the number line when using floats.

For what it’s worth, I think ofRandomInt() would be a nice function to have.

Some more trivia – while I do get 25 once in a while I have yet to get 0. So, it seems implementation-dependent:

Now I know why the ofRandom() documentation doesn’t talk about exclusive/inclusive ranges… there is no way to know!

http://www.cplusplus.com/reference/cstdlib/rand/

(ie call rand with a modulo) It might have a slight bias depending on the implementation but well, one should be extra careful if a small bias in the prng might break everything.

Do you also use rand with modulo for generating floating point values? I wonder how large your modulo has to be in order to divide it up into a float and still have enough significant digits to have a nice distribution.

Nope… I’d probably use ofRandom and don’t think too much about it.
It feels it would be two rather different use case (for instance I want to get a random element from a list rand() % size_list as opposed to I want to draw a point somewhere on screen ofRandom(0,ofGetWidth()) something like that…

Do you have a specific use case in mind or you’re just curious about prng ?

Oh, just curious. I always wondered why the ofRandom documentation didn’t mention whether the range was inclusive or exclusive. I was also using a cast ofRandom for integer things, but I am definitely going to stop doing that now.

-Nick