How many times does the following loop execute? double d; Random generator = new Random(); double x = generator.nextDouble() * 100; do { d = Math.sqrt(x) * Math.sqrt(x) - x; System.out.println(d); x = generator.nextDouble() * 10001; } while (d != 0); exactly once exactly twice can't be determined always infinite loop

Respuesta :

Answer:

The number of execution can't always be determines

Explanation:

The following points should be noted

Variable d relies on variable x (both of double data type) for its value

d is calculated as

[tex]d = \sqrt{x}^2 - x[/tex]

Mere looking at the above expression, the value of d should be 0;

However, it doesn't work that way.

The variable x can assume two categories of values

  1. Small Floating Point Values
  2. Large Floating Point Values

The range of the above values depend on the system running  the application;

When variable x assumes a small value,

[tex]d = \sqrt{x}^2 - x[/tex] will definitely result in 0 and the loop will terminate immediately because [tex]\sqrt{x}^2 = x[/tex]

When variable x assumes a large value,

[tex]d = \sqrt{x}^2 - x[/tex] will not result in 0  because their will be [tex]\sqrt{x}^2 \neq x[/tex]

The reason for this that, the compiler will approximate the value of [tex]\sqrt{x}^2[/tex] and this approximation will not be equal to [tex]x[/tex]

Hence, the loop will be executed again.

Since, the range of values variable x can assume can not be predetermined, then we can conclude that the number of times the loop will be executed can't be determined.

ACCESS MORE
EDU ACCESS