user528676
user528676

Reputation: 197

Summing array values java

I'm feeding in an array of length 8 say if trials is 100 it might be of the form 93 5 2 0 0 0 0 0, but whatever the values I have in the array I only get 0.6 back. If anyone can see if I'm making a stupid error that would be great. I've tried it with a for loop but keep getting 0.6.

static void getMetric(int[]a, int trials){
    double metric = 0;
    int i =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++;
        }
    }
}

Upvotes: 1

Views: 1682

Answers (2)

Petar Ivanov
Petar Ivanov

Reputation: 93080

You use integer division ( 5 / 3 = 1; 2 / 15 = 0).

So instead of a[0] / trials, you should have a[0] / (double) trials;

Instead of 2 / 15 you should have 2 / 15.0 etc.

Upvotes: 3

Johannes Weiss
Johannes Weiss

Reputation: 54091

It looks like you need double-division and not int-division. Remember:

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

so the following program should do the same, but more correct, I think (and shorter):

static void getMetric(int[] a, int trials){
    double metric = Math.abs((((double)a[0]) / trials) - (2 / 15));

    for (int i = 1; i < 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 that one is even more reable and robust:

static void getMetric(int[] a, int trials){
    double metric = calcMetricDiff(a[0], trials, 2.0 / 15.0);

    for (int i = 1; i < 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);
}   

Upvotes: 2

Related Questions