Question

The program is supposed to do the following:

  1. Initializes a grid of values, "ActualGridValues", (X rows by Y columns) equal to 0.
  2. Creates another grid of values, "RandomGridValues", (X rows by Y columns), defines each cell in the grid as equal to the average of N random numbers between the range of -Z to Z.
  3. Adds the number from RandomGridValues to the corresponding cell from ActualGridValues.
  4. For each cell in ActualGridValues, it also adds the values of adjacent cells.
  5. Repeats steps 2-4 ad infinitum.

The result is that random structures coalesce within the grid. Groupings of high positive values will impact nearby cells and cause them to skew high, and groupings of low negative values will do the same but skewing low.

The sum product of all the values in all the cells SHOULD be zero. Although there are localized groups of high-skewed and low-skewed numbers, over a large enough sample size the total of all cells should be zero.

The problem is that, after say, 1000 iterations, the values consistently skew negative. You have structures and locallized high and low points, but the total values always skew negative. (Which means over time the entire grid becomes filled with only negative numbers).

Every time the simulation is run, the values skew negative. Any thoughts on why?

Edit: I've isolated the issue down to the following function. The average value of all the numbers in RandomGridValue almost always turn out negative.

//For every cell value, this function generates a string of random numbers between -RandMax/2 and +RandMax/2. It then takes the average of all of these numbers. It assigns that value to a cell in the RandomGridValue array. 

function AddChaos() {
     for (var l = 0; l < GridX; l++) {
         for (var m = 0; m < GridY; m++) {
             var RandomGrid = 0;
             for (var n = 0; n < RandNums; n++) {
                 RandomGrid = RandomGrid + Math.random() * RandMax * 2 - RandMax;
             }
             RandomGridValue[l][m] = RandomGrid / RandNums;
         }
     }
 }  
Was it helpful?

Solution

Due to the floating point standard that Javascript implements, doing arithmetic with decimal values is buggy to say the least...

One work around is to convert the decimals to integers by multiplying by 100, doing the math then dividing by 100.

This only works well if you have at most 2 decimals places. If you require more precision than that, I would recommend a language other than Javascript for that part.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top