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:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# question on Math.random()

Ranch Hand
Posts: 142
• Number of slices to send:
Optional 'thank-you' note:
Hi,
This is a question from Dan's mock exam.
class SRC117 {
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?
a. b1
b. b2
c. b3
d. b4
e. b5
f. b6
g. b7
h. b8
i. b9
I selected the options b1,b6,b7,b8,b9 but the ans is b1,b7,b8,b9(b6 is not included) but why?. I know i am missing something out here but am so exhausted ,not able to figure it out.Pl. clarify.
-Sanjana

Ranch Hand
Posts: 3178
• Number of slices to send:
Optional 'thank-you' note:
Here is what I saw in the J2SE 1.4 API

random() - Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

d1 in the case of b6 may become less than 1.0, so it has chance to become true, coz d1 <= 1.0 means that d1 is less than or equal to 1.0... If some random number become less than 1.0, the boolean value b6 will become true... So b6 is excluded... Hope it is clear...

Greenhorn
Posts: 26
• Number of slices to send:
Optional 'thank-you' note:
how about b7? d1 can technically be 1.0 could it?

blacksmith
Posts: 979
• Number of slices to send:
Optional 'thank-you' note:
Luc,
In Math.random( ) 0.0 is included in the output 1.0 is never produced.
In mathematical notation random produces values in the range [0,1).
Regards,
Gian Franco

Ko Ko Naing
Ranch Hand
Posts: 3178
• Number of slices to send:
Optional 'thank-you' note:

Originally posted by luc ndabaneze:
how about b7? d1 can technically be 1.0 could it?

Luc, did u read the quote that I pasted up there? The number "1" will never be occur in the randomization... So the boolean variable b7 will never be initialized to the value true...
Hope it is clear.....
Cheers,

sanjana narayanan
Ranch Hand
Posts: 142
• Number of slices to send:
Optional 'thank-you' note:
Thanks Ko Ko Naing..
I did not look at the '<' part of it..was concentrating on the '=' part of it..
Thaks for clarifying.
-Sanjana

 I am a man of mystery. Mostly because of this tiny ad: a bit of art, as a gift, the permaculture playing cards https://gardener-gift.com