samedi 2 septembre 2023

(Java) Why does a change in how a for loop index variable counts affect a random boolean result?

Below is a simple problem written for an exercise within the old CS106A Stanford course on Java. I know the course and java version/environment are outdated, but I am starting with this just to lay a foundation of problem solving and algorithmic thinking before I move on to something more contemporary:

`import acm.util.*;
import acm.program.*;

//extends for console output
public class RadioActiveDecay extends ConsoleProgram {
//sets constant of number of inital atoms
private static final int NUM_ATOMS = 10000;
    
    public void run() {
//states intro
        println("There are " + NUM_ATOMS + " atoms initially");
//initial atom amount
        int atomsremaining = NUM_ATOMS;
//sets year variable to be added after each loop run
        int year = 0;
//sets while loop to run until there are no atoms left
            while (atomsremaining > 0) {
//sets for loop to check every atom up the amount remaining each time
                for (int i = atomsremaining; i > 0; i--) {
//checks the atom and if returned true, marks it as decayed and removes it from the remaining amount
                    if (rgen.nextDouble() < 0.5) {
                        atomsremaining--;
                    }
                }
//adds year at the end of loop
            year++;
//prints the amount of atoms remaining after each year
            println("There are " + atomsremaining + " left after year " + year);            
            }
        }
//Private random instance variables
    private RandomGenerator rgen = RandomGenerator.getInstance();
}`

My question is in regards to the for loop. As shown here and as expected, in the program the amount of atoms that decay in the first year is around 50% and they all decay around 13-15 years. However, I previously had the for loop counting in the standard positive incremental manner, i.e.: for (int = 0; i < atomsremaining; i++). When run this way, during the first year only about 30-35% of the atoms decay and they all decay in a longer amount of time, around 20-23 years. Why does this change affect the results? I can't see why having the for loop counter count up or down affects the actual random results. If this is a quirk of these old libraries or the RandomGenerator class included with them I can accept that, but if there is something fundamental I'm missing with how the loops work or the order of how the "atomsremaining" variable in that loop is subtracted I'd love to know.

I have tried changing the program to use a random boolean generator(nextBoolean) but get the same results based on how the for loop is set up. I have also previously made a separate method to generate how many atoms decay in each loop and subtract that from a separate running total of atoms but had the exact same results.




Aucun commentaire:

Enregistrer un commentaire