math - Summing array values java -


i'm feeding in array of length 8 if trials 100 might of form 93 5 2 0 0 0 0 0, whatever values have in array 0.6 back. if can see if i'm making stupid error great. i've tried loop keep getting 0.6.

static void getmetric(int[]a, int trials){     double metric = 0;     int =0;     while(i<8){         if(i==0){             double x = (a[0] / trials) - (2 / 15);             metric += math.abs(x);             i++;         }         else if(i>0 && i<7){             double x = (a[i] / trials) - 0.1;             metric += math.abs(x);             i++;         }         else{             double x = (a[7] / trials) - (2 / 15);             metric += math.abs(x);             system.out.println(""+metric);             i++;         }     } } 

it looks need double-division , not int-division. remember:

int = 96; int b = 100; double c = / b; //will 0.0! 

so following program should same, more correct, think (and shorter):

static void getmetric(int[] a, int trials){     double metric = math.abs((((double)a[0]) / trials) - (2 / 15));      (int = 1; < 7; i++) {         metric += math.abs((((double)a[i]) / trials) - 0.1);     }      metric += math.abs((((double)a[7]) / trials) - (2 / 15));      system.out.println(""+metric); } 

and 1 more reable , robust:

static void getmetric(int[] a, int trials){     double metric = calcmetricdiff(a[0], trials, 2.0 / 15.0);      (int = 1; < a.length - 1; i++) {         metric += calcmetricdiff(a[i], trials, 0.1);     }         metric += calcmetricdiff(a[a.length-1], trials, 2.0 / 15.0);      system.out.println(""+metric); }     private static double calcmetricdiff(double val, int trials, double diff) {     return math.abs((val / trials) - diff); }    

Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

c# - SharpSVN - How to get the previous revision? -

php cli reading files and how to fix it? -