开发者

Java: library to calculate the mean?

Is there a function in Jave to calculate the mean ?

I've tried by myself but I'm afraid that sum has too high value: 5 642 782 840

Can a integer be 5 642 782 840 in Java ? I don't think so...

开发者_如何学Python
for (int i = 0; i < timeValues.length; i++) {               
    sum = sum + Integer.parseInt(timeValues[i]);
}
   time = Integer.toString(sum / timeValues.length);    

thanks


//================================================= mean
public static double mean(double[] p) {
    double sum = 0;  // sum of all the elements
    for (int i=0; i<p.length; i++) {
        sum += p[i];
    }
    return sum / p.length;
}//end method mean

right off this site

after googling once Java mean


Integer can hold values between -2.147.483.648 and 2.147.483.647. Long can hold values between -9.223.372.036.854.775.808 and 9.223.372.036.854.775.807.

Thus a long would be suitable for your use case.

Another solution to do it without libraries would be to use java.math.BigInteger for your calculations. It supports even bigger numbers. At least if you don't use floating point values like float or double. Of what type are your values in the timeValues array?

If you want to use a library you may want to have a look at Apache Commons Math. To be more precise: have a look at DescriptiveStatistics and SummaryStatistics.


To build in @smas's solution

public static double mean(double[] m) {
  double sum = 0;
  for (int i = 0; i < m.length; i++) {
    sum += (double)m[i]/ (double)m.length;
  }
  return sum;
}

By dividing along the way, we can avoid the overflow issues.


Since java arrays are limited to using a 32 bit index, it is always safe for us long for computing the sum of an array of int or Integer, on the other hand, if you need to compute the sum or average of an array of long or a collection then you might want to use java.math.BigInteger

Chris has the generally correct answer, but since you appear to be using an array of strings

public static double meanOfStrings(String[] p) {
  long sum = 0;  // sum of all the elements
  for (int i=0; i<p.length; i++) {
     sum += Long.parseLong(p[i]);
  }
  return ((double) sum) / p.length;
}


For simple use:

public static double mean(double[] m) {
    double sum = 0;
    for (int i = 0; i < m.length; i++) {
        sum += m[i];
    }
    return sum / m.length;
}

For advanced use try some library: Have look at Apache Commons Math


Contrary to what other people say, I'm pretty sure a long can hold that high numbers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜