My while loop has run into an infinite loop...?
I have to write a program that computes a close enough value for the half-life of carbon-14 using comparison of floating point numbers. The while loop should be controlled by a comparison of half of the initial amount and the computed amount remaining. I'm confused as to how to get the number of years because my while loop becomes infinite and I dont know how to stop it. The value should be around 5000 years. Thanks for any help, I really appreciate it!
Code Java:
public class Lab321
{
public static void main(String[] args)
{
final double EPSILON = 1.0E-7;
final double DECAY = 1.14E-4;
double initialAmount = 2.0E-5;
double computedAmount = initialAmount - (DECAY / 100) * initialAmount;
int year = 0;
while (Math.abs(computedAmount - 1.0E-5) > EPSILON)
{
year++;
double amountRemaining = initialAmount - (DECAY / 100) * initialAmount;
System.out.println(amountRemaining);
}
System.out.println("The approximate value for the half life of carbon-14 is " + year + " years.");
}
}
Re: My while loop has run into an infinite loop...?
At no point in your loop are you modifying the value of computedAmount. Also, even if you replaced amountRemaining with computedAmount, the value you're assigning is an unchanging value.
Re: My while loop has run into an infinite loop...?
Well I modified my code and I'm finally getting a number for years. But it's a very big number, about 599296 years.
This is my modified code...
Code Java:
public class Lab321
{
public static void main(String[] args)
{
final double EPSILON = 1.0E-7;
final double DECAY = 1.14E-4;
final double INITIAL_AMOUNT = 2.0E-5;
final double IDEAL = 2.0E-5 / 2;
double amount = INITIAL_AMOUNT;
int year = 0;
while (Math.abs(amount - IDEAL) > EPSILON)
{
year++;
double decay = DECAY / 100 * amount;
amount = amount - decay;
}
System.out.println("The approximate value for the half life of carbon-14 is " + year + " years.");
}
}
Re: My while loop has run into an infinite loop...?
without knowing the specifics of how you're calculating the half-life, it's difficult to figure out what's wrong. However, I suspect that the problem is dividing by 100 as your ~100x off.