1

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++;
        }
    }
}
2
  • Does this method return 0.6 all the time? It doesn't seem to have a return value, so where are you seeing 0.6? Commented Jul 3, 2011 at 11:06
  • Sorry I meant it prints 0.6 each time at the print line Commented Jul 3, 2011 at 11:07

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

double x = (double)((a[7] / trials) - (2 / 15)) ?
Isn't it : a[0] / (double) trials ?
no, this doesn't work: (double)(2 / 15) == 0.0, because it first does the integer division and then convert to double
2

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);
}   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.