It seems that you're using an outdated browser. Some things may not work as they should (or don't work at all).
We suggest you upgrade newer and better browser like: Chrome, Firefox, Internet Explorer or Opera

×
I'm working on creating procedurally generated heightmaps, and am using the Linear Congruential Generator formula to generate psuedorandom numbers. The problem is, I can't figure out how you limit the output to a certain range (i.e, only numbers from 1 to 30, or something like that). Does anyone know how I'd do this?

LINK:

http://www1.i2r.a-star.edu.sg/~knandakumar/nrg/Tms/Probability/Probgenerator.htm


(explains how the formula works, and tells how to limit the ranges... but in a way I don't understand :P. Math isn't my forte, you see).
No posts in this topic were marked as the solution yet. If you can help, add your reply
ahh, never mind. The java Random() class uses this formula anyway, so I can just plug that in.
avatar
jefequeso: ahh, never mind. The java Random() class uses this formula anyway, so I can just plug that in.
In Java the RNG generates between 0 and 1 generally. So if you want a value of 1-X you multiply the output by X (in your case 30), then truncate, then add 1, voila, a random value from 1-30.
They are using modular arithmetic to achieve a desired range. The equation gives you a range from zero to "M". In particular, you can see this is done in the "mod M" at the end of the equation. Basically, the left portion of the equation (i.e. the portion in parenthesis) is calculated and then the modulo operation is performed to the result

A brief description in case you are unfamiliar with modular arithmetic. The modulo operation solves for the remainder between the division of two numbers. For example, 5 mod 2=1, 1 mod 2=1, 6 mod 2=2, and 2 mod 2=2. The resulting answer will be between 0 and whatever mod value is used (excluding the value itself since x mod x=0). For more examples, I refer you to the google search engine; it is capable of performing this kind of math.

In this particular application, the choice of M limits the upper range of the output because there cannot be any remainders equal to or greater than M. I suggest you choose M to be 1 greater than the largest value you want.