I use a while() loop to keep adding up random doubles to x until x reaches a particular distance from origin. It stops running without any output. If I change the while() loop to while (Math.abs(x) == distance), it gives me output though not the right one I want. What is wrong with these code? Thanks for any of your input.
while (Math.abs(x) != distance) { randValue = (-1.0) + 2.0 * rand.nextDouble(); x = x + randValue; move = move +1; } System.out.println("After " + move + " moves X now at " + x);
You're checking whether the value is exactly the distance required. You need to check whether it's reached or exceeded the required distance:
while (Math.abs(x) < distance)
In general, using ==
or !=
with floating point values is a bad idea - after you've performed some operations, you'll often find that a value is close to the expected one, but not exactly right. If you want to check whether one value is "pretty much equal to" another one, you need to define a particular tolerance and check that. I don't think that's required in your situation though.
See more on this question at Stackoverflow