Android examples for java.lang:Math
lin Regression
//package com.java2s; import android.util.Log; public class Main { private static String logtag = "MU"; public static double[] linRegression(double[] dists, double[] concs) { int n = dists.length; if (dists.length != concs.length) { Log.e(logtag, "Both input arrays must be the same length."); }// w w w . ja v a2s .c om // first pass: read in data, compute xbar and ybar double sumx = 0.0, sumy = 0.0, sumx2 = 0.0, sumxy = 0.0; for (int i = 0; i < dists.length; i++) { sumx += concs[i]; sumx2 += concs[i] * concs[i]; sumy += dists[i]; sumxy += dists[i] * concs[i]; } Log.d(logtag, "sumx2=" + sumx2 + " sumy=" + sumy); double xbar = sumx / n; double ybar = sumy / n; // second pass: compute summary statistics double xxbar = 0.0, yybar = 0.0, xybar = 0.0; for (int i = 0; i < n; i++) { xxbar += (concs[i] - xbar) * (concs[i] - xbar); yybar += (dists[i] - ybar) * (dists[i] - ybar); xybar += (concs[i] - xbar) * (dists[i] - ybar); } Log.d(logtag, "xxbar=" + xxbar + " xybar=" + xybar + " yybar =" + yybar); double[] coeffs = new double[5]; coeffs[0] = xybar / xxbar; coeffs[2] = ybar - coeffs[0] * xbar; // print results Log.d(logtag, "y = " + coeffs[0] + " * x + " + coeffs[2]); // analyze results int df = n - 2; double rss = 0.0; // residual sum of squares double ssr = 0.0; // regression sum of squares for (int i = 0; i < n; i++) { double fit = coeffs[0] * concs[i] + coeffs[1]; rss += (fit - dists[i]) * (fit - dists[i]); ssr += (fit - ybar) * (fit - ybar); } double R2 = ssr / yybar; coeffs[4] = R2; double svar = rss / df; double svar1 = svar / xxbar; coeffs[1] = svar1; double svar0 = svar / n + xbar * xbar * svar1; coeffs[3] = svar0; Log.d(logtag, "R^2 = " + R2); Log.d(logtag, "std error of beta_1 = " + Math.sqrt(svar1)); Log.d(logtag, "std error of beta_0 = " + Math.sqrt(svar0)); svar0 = svar * sumx2 / (n * xxbar); Log.d(logtag, "std error of beta_0 = " + Math.sqrt(svar0)); Log.d(logtag, "SSTO = " + yybar); Log.d(logtag, "SSE = " + rss); Log.d(logtag, "SSR = " + ssr); return coeffs; } }