Bom dia para todos vocês, estou com uma dúvida meio besta. Não entendo porque o código abaixo não funciona:
Random floater = new Random();
float teste = (float)10 + floater.nextFloat(90);
Sei que pode funcionar assim:
Random floater = new Random();
float teste = (float)10 + floater.nextFloat();
Eu só quero sortear um número entre 10 e 90.2f por exemplo…
Alguma dica?
Pessoal, acho que eu saquei… o nextFloat() só pode retornar um valor entre 0.0 e 1.0…ou seja não tem como inserir outro valor dentro…
Na página da sun:http://java.sun.com/j2se/1.4.2/docs/api/java/util/Random.html
Esta escrito o seguinte:
nextFloat
public float nextFloat()
Returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence.
The general contract of nextFloat is that one float value, chosen (approximately) uniformly from the range 0.0f (inclusive) to 1.0f (exclusive), is pseudorandomly generated and returned. All 224 possible float values of the form m x 2-24, where m is a positive integer less than 224 , are produced with (approximately) equal probability. The method nextFloat is implemented by class Random as follows:
public float nextFloat() {
return next(24) / ((float)(1 << 24));
}
The hedge "approximately" is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source or randomly chosen bits, then the algorithm shown would choose float values from the stated range with perfect uniformity.
[In early versions of Java, the result was incorrectly calculated as:
return next(30) / ((float)(1 << 30));
This might seem to be equivalent, if not better, but in fact it introduced a slight nonuniformity because of the bias in the rounding of floating-point numbers: it was slightly more likely that the low-order bit of the significand would be 0 than that it would be 1.]
Returns:
the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence.
Resolução do meu Problema:
Random floater = new Random();
for(int x = 0; x < 10; x++)
{
float teste = (10 + floater.nextInt(30)) + (floater.nextFloat());
System.out.println(teste);
}
Se você quer sortear um número entre 10 e 90 (com distribuição uniforme), então é necessário usar:
double d = 10.0 + (90.0 - 10.0) * Math.random();
O jeito que você fez nunca vai sortear um número superior a 10 + 29 + 1 = 40.
Muito grato pela dica…agora preciso entender a solução que você deu…valeu muito…