1

I am using an internal language in my company and they only have Random() that returns a float between 0 and 1.

I need to port a piece of C++ code that use rand():

int b = rand() % (i+1); 

I looked at the docs, but not sure how I can use my Random() to generate a number between 0 and i+1 which is what the above code does, right?

I tried multiplying i+1 with Random() but didn't get the same results, that's why I am not sure if what I am doing is correct.

I expect difference between the results due to different random functions, but still I want to be sure I am translating it correctly.

2 Answers 2

4

You need to multiply Random() with i and not i+1.

C++ rand() returns an integer between 0 and RAND_MAX but your Random() returns a float between 0 and 1, so multiplying the output of Random() with i and taking the integer portion of the result will give you an integer in [0,i] which is what rand() %(i+1) gives.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks I don't understand why the original code uses i+1 though? It loops backwards starting with the last index, so wouldn't i+1 give an index larger than the max index which is (num_items - 1)?
(a +ve int) % N returns a number between 0 and N-1 (both inclusive).
If the original said rand() % (i + 1) then you definitely want to replace it with Random()*(i + 1). I'm willing to be that Random() produces a number in the range [0, 1) , so multiplying by i produces the range [0, i) and truncating to int will result in [0, i-1].
@rici, If you're unsure whether Random() could return 1.0 or not you can multiply by i+0.999999999999999 instead of i+1.
2

Rand() give you a number between 0 and RAND_MAX, which after applying the mod operator you end up with a number between 0 and i (including i).

To do the same with Random() you'll need to multiply by ( i+1 ), then take the floor of that (round down):

b = floor( Random() * (i+1) ) 

This will give you a number from 0 to i (including the fence posts) as required.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.