fork download
  1. public class Main
  2. {
  3. public static void main(String[] args) {
  4. int numOfData = 5000;
  5. int[] x = new int[numOfData];
  6. int[] y = new int[numOfData];
  7. for (int i=0; i<numOfData; i++) {
  8. x[i] = 2*(i+1) + 1;
  9. y[i] = (x[i]*x[i] - 5) / 4;
  10. }
  11. double[] ln_x = new double[numOfData];
  12. double[] ln_y = new double[numOfData];
  13. for (int i=0; i<numOfData; i++) {
  14. ln_x[i] = Math.log(x[i]);
  15. ln_y[i] = Math.log(y[i]);
  16. }
  17. double sum_ln_x = 0.0, sum_ln_y = 0.0;
  18. for (int i=0; i<numOfData; i++) {
  19. sum_ln_x += ln_x[i];
  20. sum_ln_y += ln_y[i];
  21. }
  22. double mean_ln_x = sum_ln_x / numOfData, mean_ln_y = sum_ln_y / numOfData;
  23. double[] ln_x_minus_mean = new double[numOfData];
  24. double[] ln_y_minus_mean = new double[numOfData];
  25. for (int i=0; i<numOfData; i++) {
  26. ln_x_minus_mean[i] = ln_x[i] - mean_ln_x;
  27. ln_y_minus_mean[i] = ln_y[i] - mean_ln_y;
  28. }
  29. double sum_sqr_ln_x_minus_mean = 0.0, sum_sqr_ln_y_minus_mean = 0.0, sum_products_x_y = 0.0;
  30. for (int i=0; i<numOfData; i++) {
  31. sum_sqr_ln_x_minus_mean += Math.pow(ln_x_minus_mean[i], 2.0);
  32. sum_sqr_ln_y_minus_mean += Math.pow(ln_y_minus_mean[i], 2.0);
  33. sum_products_x_y += ln_x_minus_mean[i] * ln_y_minus_mean[i];
  34. }
  35. double a, b, r, r2;
  36. b = sum_products_x_y / sum_sqr_ln_x_minus_mean;
  37. a = Math.exp(mean_ln_y - b*mean_ln_x);
  38. r = sum_products_x_y / (Math.sqrt(sum_sqr_ln_x_minus_mean)*Math.sqrt(sum_sqr_ln_y_minus_mean));
  39. r2 = Math.pow(r, 2.0);
  40. System.out.format("a=%f b=%f r=%f r2=%f", a, b, r, r2);
  41. }
  42. }
Success #stdin #stdout 0.12s 56196KB
stdin
Standard input is empty
stdout
a=0.245987 b=2.001935 r=0.999982 r2=0.999964