• Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Dennis Von Valkenburgh
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!