Win a copy of Rust Web Development this week in the Other Languages forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Tim Cooke
• Campbell Ritchie
• Ron McLeod
• Liutauras Vilda
• Jeanne Boyarsky
Sheriffs:
• Junilu Lacar
• Rob Spoor
• Paul Clapham
Saloon Keepers:
• Tim Holloway
• Tim Moores
• Jesse Silverman
• Stephan van Hulst
• Carey Brown
Bartenders:
• Al Hobbs
• Piet Souris
• Frits Walraven

# Math.random()

Greenhorn
Posts: 17
• Number of slices to send:
Optional 'thank-you' note:
class test {
public static void main (String[] args) {
double d1 = Math.random();
boolean b1 = (d1 < 0.0), b2 = (d1 <= 0.0), b3 = (d1 == 0.0);
boolean b4 = (d1 >= 0.0), b5 = (d1 < 1.0), b6 = (d1 <= 1.0);
boolean b7 = (d1 == 1.0), b8 = (d1 >= 1.0), b9 = (d1 > 1.0);
}}

Which of the boolean variables will never be initialized to the value true?

but i am getting result as b1,b2,b3,b7,b8,b9.could someone explain how it is right for b3 and wrong for b6

Sheriff
Posts: 11343
• Number of slices to send:
Optional 'thank-you' note:
As you know, Math.random() generates a double between zero and one -- including zero, but not including one.

(d1 <= 0.0)...

Note that <= implies an "or" condition: Less than or equal to. We need only one or the other to be true in order for the evaluation to be true. In this case, the number will never be "equal to" 1.0, but it will always be "less than" 1.0. Therefore, the test <= will always be true.

(d1 == 0.0)...

In theory, Math.random() might be exactly 0.0. But what are the odds of this really happening?

lavanya sankuappan
Greenhorn
Posts: 17
• Number of slices to send:
Optional 'thank-you' note: