Hi, I've set up my Randomwalk program and it's working wonders. Before going to my question, I'd like to quickly introduce what my randomwalk program does:
It has two main parts in the code, the Steps part and the Walks part. It has 500 steps per walk, and 1000 walks in total. In each walk it can either go left or right (-1 or +1) and after 500 steps, it'll end up in a random location (most likely between -30 and + 30 and most likely near 0). This "end location" L will be outputted 1000 times, and then the program will output how many times it landed in -500 to +500 ( like it landed it 4 ten times).
My teacher just told me that I need to implement a new feature. That feature is finding the average value. This is found by:
I need to say (let's call it a) a = ((Where it landed * how many times it landed on that spot)+(Where it landed+1 * how many times it landed on that spot+1)+..)/number of walks, in this case 1000)
Example: a = ((-500*0)+(-499*0)...(10*3)...(500*0))/(1000)
In the example, you can see that it starts off saying that a equals how many times it landed on -500*-500 and so on until it reaches how many times it landed on +500*500, then divided by the number of walks, which is 1000.
I'm not sure how to implement this feature, so I'd be grateful if you could help me Heres the full code:
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.util.HashMap; public class RandomWalk { public static final int NBR_WALKS = 1000; public static final int NBR_STEPS = 500; public static void main(String[] args) { /*PrintStream out; try { out = new PrintStream(new FileOutputStream("/Volumes/DATA/Desktop/RandomWalkResultater.txt", true)); System.setOut(out); } catch (FileNotFoundException e) { e.printStackTrace(); }*/ HashMap<Integer, Integer> totals = new HashMap<>(); for (int i = -NBR_STEPS; i <= NBR_STEPS; i++) { totals.put(i, 0); } System.out.println(""); for (int i = 0; i < NBR_WALKS; i++) { int total_value = 0; for (int j = 0; j < NBR_STEPS; j++) { int L = (int) (Math.random() * 2); total_value += (L == 0) ? -1 : 1; } System.out.println("For randomwalk number " + i + " the end point was " + total_value); totals.put(total_value, totals.get(total_value) + 1); } System.out.println(" "); for (int i = -500; i < 500; i++) { System.out.println("You landed on the end point "+i+" the following times: "+totals.get(i)); } System.out.println(" "); System.out.println("For the excel program:"); System.out.println("x-values:"); for (int i = -500; i < 500; i++) { System.out.println(i); } System.out.println(""); System.out.println("y-values:"); for (int i = -500; i < 500; i++) { System.out.println(totals.get(i)); } } }