programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Ron McLeod
• Paul Clapham
• Bear Bibeault
• Junilu Lacar
Sheriffs:
• Jeanne Boyarsky
• Tim Cooke
• Henry Wong
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Tim Holloway
• salvin francis
• Frits Walraven
Bartenders:
• Scott Selikoff
• Piet Souris
• Carey Brown

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

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!

Marshal
Posts: 70228
282
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: 70228
282
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

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

Henry