Write a program that simulates the decay of a sample that contains 10,000 atoms of
radioactive material, where each atom has a 50 percent chance of decaying in a year.
The output of your program should show the number of atoms remaining at the end
of each year
import acm.program.*;
import acm.util.*;
public class atoms extends ConsoleProgram {
public void run() {
int total = 10000;
int count = 0;
while (total > 0) {
count++;
if (total == 10000) {
println("There are " + total + " atoms initially.");
}
total = (halfMinus(total));
println("There are " + total + " atoms at the end of year " + count);
}//ends while
} //ends run
private int halfMinus (int number) {
int difference;
if (number < 30) {
difference = rgen.nextInt(1,3);
} else {
difference = rgen.nextInt(12,31);
}
int choice = rgen.nextInt(1,2);
if (choice == 1) {
number -= difference;
} else {
number += difference;
}
number /= 2;
return number;
}
RandomGenerator rgen = new RandomGenerator();
}//ends class
While this does give me the result I'm looking for, I am not satisfied with it 100% of the time. The issue is when it gets down to the lower numbers, sometimes when it hits 2,1 or 0, it will go for a few more rounds.
Anyway, this serves its purpose.
No comments:
Post a Comment