Tilted Forum Project Discussion Community

Tilted Forum Project Discussion Community (https://thetfp.com/tfp/)
-   Tilted Technology (https://thetfp.com/tfp/tilted-technology/)
-   -   [java] Random Number Generation (https://thetfp.com/tfp/tilted-technology/46447-java-random-number-generation.html)

CSflim 02-21-2004 12:05 PM

[java] Random Number Generation
 
I'm writing a program which needs to generate random numbers.

Math.random() returns a double between 0.0 and 1.0

#1.
I need to generate a random integer between 0 and n, with equal probability for each.

If I use
Math.random() * n
it means there is an infinitesimal chance of getting n (as the random function must evaluate to 1.0...very unlinkely)

so then I decided to use
(Math.random() * Integer.MAX_VALUE) % n
which will generate any integer between 0 and n, with reasonably equal probability...but not necessarily exactly (depending on the values of n and Integer.MAX_VALUE).

As it happens, I'm not too concerned with the evenness, but out of curiosity, if I NEEDED perfectly even distribution among the various values between 0 and n, how would I do it?

#2
I need to generate numbers, with different values having different probabilities of occuring.

I can think of no elegant way of doing it.
One way of doing it, is to construct an array, with each integer between 0 and n, occruing the number of times equal to its weight...

e.g.:
int[] bob = {0,0,0,1,2,3,3,3,3,4,5,5}
would give
0 weight: 3
1 weight: 1
2 weight: 1
3 weight: 4
4 weight: 1
5 weight: 2

and then generate a num between 0 and bob.length (as above), and use that to index the array, and thus generate a number between 0 and n, with the correct weightings.

is there a better way to do this?

#3
Anyone know where I can get a list of the relative frequenciy of occurance of each letter of the alphabet in english?

bellzboy 02-21-2004 11:40 PM

for the first, import java.util.Random;

Random gen = new Random();
gen.NextInt(n+1);

gen is merely the name of the random generator, I use gen, call it whatever you want. *edit* sorry, you know that I'm sure, it's just a constructor. Didnt mean to insult your intelligence.

for the second, generate a random number between say 1 and 100, then use if statements, if its between 1 and 30, its 1, 31-40 its 2, etc. gives one a 30% chance, 2 a tne percent chance. That is the only way I can think of, I don't know whether it would be any easier.

for the third, perhaps this will help:
http://www.askoxford.com/asktheexper...ords/frequency


All times are GMT -8. The time now is 02:42 AM.

Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2025, vBulletin Solutions, Inc.
Search Engine Optimization by vBSEO 3.6.0 PL2
© 2002-2012 Tilted Forum Project


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43