CATEGORII DOCUMENTE |
Asp | Autocad | C | Dot net | Excel | Fox pro | Html | Java |
Linux | Mathcad | Photoshop | Php | Sql | Visual studio | Windows | Xml |
The statement:
char c = (char)(Math.random() * 26 + 'a');
deserves a closer look. Math.random( ) produces a double, so the value 26 is converted to a double to perform the multiplication, which also produces a double. This means that 'a' must be converted to a double to perform the addition. The double result is turned back into a char with a cast.
First, what does the cast to char do? That is, if you have the value 29.7 and you cast it to a char, is the resulting value 30 or 29? The answer to this can be seen in this example:
//: CastingNumbers.java
// What happens when you cast a float or double
// to an integral value?
public class CastingNumbers
The output is:
above: 0.7
below: 0.4
(int)above: 0
(int)below: 0
(char)('a' + above): a
(char)('a' + below): a
So the answer is that casting from a float or double to an integral value always truncates.
The second question has to do with Math.random( ). Does it produce a value from zero to one, inclusive or exclusive of the value '1'? In math lingo, is it (0 ), or [0,1], or (0,1] or [0,1)? (The square bracket means "includes" whereas the parenthesis means "doesn't include.") Again, a test program provides the answer:
//: RandomBounds.java
// Does Math.random() produce 0.0 and 1.0?
public class RandomBounds
public static void main(String[] args)
else if(args[0].equals('upper'))
else
usage();
}
To run the program, you type a command line of either:
java RandomBounds lower
or
java RandomBounds upper
In both cases you are forced to break out of the program manually, so it would appear that Math.random( ) never produces either 0.0 or 1.0. But this is where such an experiment can be deceiving. If you consider that there are 2128 different double fractions between 0 and 1, the likelihood of reaching any one value experimentally might exceed the lifetime of one computer, or even one experimenter. It turns out that 0.0 is included in the output of Math.random( ). Or, in math lingo, it is [0 ).
Politica de confidentialitate | Termeni si conditii de utilizare |
Vizualizari: 658
Importanta:
Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved