PDA

View Full Version : to get random values in Java


taegi
10-06-2005, 05:44 AM
How can I get values of -26 to 37.5 with random class in Javafor example,
num = generator.nextFloat(63.5) - 26; this way does not work because it is float in ().

Anybody know that?

fred_lemaster
10-06-2005, 06:37 AM
Let's say your rand() function gives values in a range of integers from 0 to the value of the parameter - rand(4) could give 0, 1, 2, 3, or 4 for example. If you needed a range that included negatives and one decimal place, you could make a new function that accepted a maximum and a minimum and scaled the values of rand() accordingly. To get a decimal place, you could take the rand() of 10 times the max and divide the result by 10. To scale the function, it could add the minimum to the result and take the rand of maximum - minimum, or in psuedocode function myrand( min, max ) {
return ( (10 * min) + rand(10 * (max - min)) ) / 10;
}
Now I don't know if that's how rand is defined in Java, but this is an example of one way to scale a rand() function to a range different than its default. It's sort of like manipulating trig functions from highschool.

arramor
10-10-2005, 08:22 AM
heya, here is a solution in java, didn't test very throughly


double min = -26, max = 37.5;

double result = Math.random()*(max-min) + min;

Trident_2K5
10-10-2005, 12:19 PM
Although it's a a bit more complex you may want to use Random.nextDouble() or SecureRandom.nextDouble(), latter has pluggable algorithms. Another plus is what you can manipulate seeds easier and serialize.
http://java.sun.com/j2se/1.4.2/docs/api/java/security/SecureRandom.html

CGTalk Moderation
10-10-2005, 12:19 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.