programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Array of numbers, not able to get the correct average value

Dennis Von Valkenburgh
Ranch Hand
Posts: 126
Hello,
I have the following methods:

The input is the following arary (Its from the Junit test that fails this): [Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE]
I get an average of 0.0 when it should be -0.2.

Any Idea why? Thanks!

Campbell Ritchie
Marshal
Posts: 56536
172
What is wrong? Is it that you are not getting a fractional number?

You might be assigning to a double, but your formula uses integer arithmetic throughout; you can only ever get whole number results if you use integer arithmetic.
I suggest you should use a for‑each loop rather than a plain for, or even a Stream and its average method.

Dennis Von Valkenburgh
Ranch Hand
Posts: 126
Campbell Ritchie wrote:What is wrong? Is it that you are not getting a fractional number?

You might be assigning to a double, but your formula uses integer arithmetic throughout; you can only ever get whole number results if you use integer arithmetic.
I suggest you should use a for‑each loop rather than a plain for, or even a Stream and its average method.

The thing is we cannot use the stream average method but have to write our own.
So I should change the datatypes for the values?

Dennis Von Valkenburgh
Ranch Hand
Posts: 126
Ok got it:
public static double getAverage(int[] data) {
double sum = getSum(data);
double avg = 0;
double size = data.length;
avg = sum / size;
return avg;
}

Just created a new variable called sum with the double datatype and it works now.
Thanks!

Campbell Ritchie
Marshal
Posts: 56536
172
Another way to do it is to insert a double into the arithmetic somewhere. Instead of
avg = getSum(data) / size;
try
avg = 1.0 * getSum(data) / size;
Or try a cast (see below).
By the way you can shorten that method no endor

Henry Wong
author
Sheriff
Posts: 23295
125
BTW, the getSum ( ) method both overflowed and underflowwed with the example data. If only one happened, then the results would have been incorrect.

Henry

 It is sorta covered in the JavaRanch Style Guide.