歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Commons Math學習筆記

先列出一個目錄:(這個目錄是根據commons math 3.3庫的結構設計的)

Section 1 linear 線性代數(矩陣為主)

1) Vector 向量

2) Matrix 矩陣

3) Matrix Decomposition 矩陣分解

Section 2 analysis 數學分析(函數為主)

1) Function 函數

2) Polynomial 多項式函數

3) Interpolation 插值

4) Integration 積分

5) Solver 求解

Section 3 Probabilityand Statistics 概率和統計

      1)distribution 分布

      2)fraction and complex 分數和復數

      3)random and statistics 隨機生成和統計初步
   
      4)cluster and regression聚類和回歸

1.分布

package apache.commons.math.test;

import org.apache.commons.math3.distribution.NormalDistribution;
import org.apache.commons.math3.distribution.PoissonDistribution;
import org.apache.commons.math3.exception.MathArithmeticException;

/**
 *
 * @ClassName: DistributionTest
 * @Description: 分布
 * @author zengfh
 * @date 2014年11月21日 下午3:32:15
 *
 */
public class DistributionTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  poisson();
  System.out.println("------------------------------------------");
  normal();
  test();
 }

 /**
  * test for example 《飲料裝填量不足與超量的概率》
  * 某飲料公司裝瓶流程嚴謹,每罐飲料裝填量符合平均600毫升,標准差3毫升的常態分配法則
  * 。隨機選取一罐,容量超過605毫升的概率?容量小於590毫升的概率 容量超過605毫升的概率 = p ( X > 605)= p ( ((X-μ)
  * /σ) > ( (605 – 600) / 3) )= p ( Z > 5/3) = p( Z > 1.67) = 0.0475
  * 容量小於590毫升的概率 = p (X < 590) = p ( ((X-μ) /σ) < ( (590 – 600) / 3) )= p ( Z
  * < -10/3) = p( Z < -3.33) = 0.0004
  */
 private static void test() {
  // TODO Auto-generated method stub
  NormalDistribution normal = new NormalDistribution(600, 3);
  try {
   System.out.println("P(X<590) = "
     + normal.cumulativeProbability(590));
   System.out.println("P(X>605) = "
     + (1 - normal.cumulativeProbability(605)));
  } catch (MathArithmeticException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 private static void poisson() {
  // TODO Auto-generated method stub
  PoissonDistribution dist = new PoissonDistribution(4.0);
  try {
   System.out.println("P(X<=2) = " + dist.cumulativeProbability(2));
   System.out.println("mean value is " + dist.getMean());
   System.out.println("P(X=1) = " + dist.probability(1));
   System.out.println("P(X=x)=0.8 where x = "
     + dist.inverseCumulativeProbability(0.8));
  } catch (MathArithmeticException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 private static void normal() {
  // TODO Auto-generated method stub
  NormalDistribution normal = new NormalDistribution(0, 1);
  try {
   System.out.println("P(X<2.0) = "
     + normal.cumulativeProbability(2.0));
   System.out.println("mean value is " + normal.getMean());
   System.out.println("standard deviation is "
     + normal.getStandardDeviation());
   System.out.println("P(X=1) = " + normal.density(1.0));
   System.out.println("P(X<x)=0.8 where x = "
     + normal.inverseCumulativeProbability(0.8));
  } catch (MathArithmeticException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

2.函數積分

package apache.commons.math.test;

import org.apache.commons.math3.analysis.UnivariateFunction;
import org.apache.commons.math3.analysis.function.Sin;
import org.apache.commons.math3.analysis.integration.BaseAbstractUnivariateIntegrator;
import org.apache.commons.math3.analysis.integration.SimpsonIntegrator;
import org.apache.commons.math3.exception.ConvergenceException;

/**
 *
 * @ClassName: IntegrationTest
 * @Description: 函數積分
 * @author zengfh
 * @date 2014年11月21日 下午2:59:58
 *
 */
public class IntegrationTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  integration();
 }

 private static void integration() {
  // TODO Auto-generated method stub
  UnivariateFunction f = new Sin();
  BaseAbstractUnivariateIntegrator integrator = new SimpsonIntegrator();

  // integrate
  System.out.println("f(x)=sin(x)");
  try {
   System.out.println("integration of f(x) from 0 to Pi is "
     + integrator.integrate(100,f, 0, Math.PI));
  } catch (ConvergenceException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalArgumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

3.函數插值

package apache.commons.math.test;

import org.apache.commons.math3.analysis.UnivariateFunction;
import org.apache.commons.math3.analysis.interpolation.SplineInterpolator;
import org.apache.commons.math3.analysis.interpolation.UnivariateInterpolator;
import org.apache.commons.math3.analysis.polynomials.PolynomialFunction;
import org.apache.commons.math3.analysis.polynomials.PolynomialFunctionLagrangeForm;
import org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction;
import org.apache.commons.math3.exception.MathArithmeticException;

/**
 *
 * @ClassName: InterpolationTest
 * @Description: 函數插值
 * @author zengfh
 * @date 2014年11月21日 下午3:13:39
 *
 */
public class InterpolationTest {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  polynomialsInterpolation();
  System.out.println("-------------------------------------------");
  interpolatioin();
 }

 private static void interpolatioin() {
  // TODO Auto-generated method stub
  // double x[] = { 0.0, 0.5, 1.0 };
  // double y[] = { 0.0, 0.5, 1.0 };
  double x[] = { 0.0, Math.PI / 6d, Math.PI / 2d, 5d * Math.PI / 6d,
    Math.PI, 7d * Math.PI / 6d, 3d * Math.PI / 2d,
    11d * Math.PI / 6d, 2.d * Math.PI };
  double y[] = { 0d, 0.5d, 1d, 0.5d, 0d, -0.5d, -1d, -0.5d, 0d };
  UnivariateInterpolator i = new SplineInterpolator();
  UnivariateFunction f = null;
  // interpolate y when x = 0.5
  try {
   f = i.interpolate(x, y);
   System.out.println("when x = 0.5, y = " + f.value(0.5));
  } catch (MathArithmeticException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  // check polynomials functions
  PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f)
    .getPolynomials();
  for (int j = 0; j < polynomials.length; j++) {
   System.out
     .println("cubic spline:f" + j + "(x) = " + polynomials[j]);
  }
 }

 private static void polynomialsInterpolation() {
  // TODO Auto-generated method stub
  double x[] = { 0.0, -1.0, 0.5 };
  double y[] = { -3.0, -6.0, 0.0 };
  PolynomialFunctionLagrangeForm p = new PolynomialFunctionLagrangeForm(
    x, y);
  // output directly
  System.out.println("ugly output is " + p);
  // interpolate y when x = 1.0
  try {
   System.out.println("when x = 1.0, y = " + p.value(1.0));
  } catch (MathArithmeticException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  // degree
  System.out.println("polynomial degree is " + p.degree());
  // coefficients
  for (int i = 0; i < p.getCoefficients().length; i++) {
   System.out.println("coeff[" + i + "] is " + p.getCoefficients()[i]);
  }
  //
 }

}

4.多項式函數

package apache.commons.math.test;

import org.apache.commons.math3.analysis.polynomials.PolynomialFunction;
import org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction;

/**
 *
 * @ClassName: PolinomialsFunctionTest
 * @Description: 多項式函數
 * @author zengfh
 * @date 2014年11月21日 下午1:38:13
 *
 */
public class PolinomialsFunctionTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  polynomials();
  System.out.println("-----------------------------------------------");
  polynomialsSpline();
 }

 private static void polynomialsSpline() {
  // TODO Auto-generated method stub
  PolynomialFunction[] polynomials = {
    new PolynomialFunction(new double[] { 0d, 1d, 1d }),
    new PolynomialFunction(new double[] { 2d, 1d, 1d }),
    new PolynomialFunction(new double[] { 4d, 1d, 1d }) };
  double[] knots = { -1, 0, 1, 2 };
  PolynomialSplineFunction spline = new PolynomialSplineFunction(knots,
    polynomials);
  // output directly
  System.out.println("poly spline func is " + spline);
  // get the value when x = 0.5
  try {
   System.out.println("f(0.5) = " + spline.value(0.5));
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  // the number of spline segments
  System.out.println("spline segments number is " + spline.getN());
  // the polynomials functions
  for (int i = 0; i < spline.getN(); i++) {
   System.out.println("spline:f" + i + "(x) = "
     + spline.getPolynomials()[i]);
  }
  // function derivative
  System.out.println("spline func derivative is " + spline.derivative());
 }

 private static void polynomials() {
  // TODO Auto-generated method stub
  double[] f1_coeff = { 3.0, 6.0, -2.0, 1.0 };
  double[] f2_coeff = { 1.0, 2.0, -1.0, -2.0 };
  PolynomialFunction f1 = new PolynomialFunction(f1_coeff);
  PolynomialFunction f2 = new PolynomialFunction(f2_coeff);
  // output directly
  System.out.println("f1(x) is : " + f1);
  System.out.println("f2(x) is : " + f2);
  // polynomial degree
  System.out.println("f1(x)'s degree is " + f1.degree());
  // get the value when x = 2
  System.out.println("f1(2) = " + f1.value(2));
  // function add
  System.out.println("f1(x)+f2(x) = " + f1.add(f2));
  // function substract
  System.out.println("f1(x)-f2(x) = " + f1.subtract(f2));
  // function multiply
  System.out.println("f1(x)*f2(x) = " + f1.multiply(f2));
  // function derivative
  System.out.println("f1'(x) = " + f1.derivative());
  System.out.println("f2''(x) = "
    + ((PolynomialFunction) f2.derivative()).derivative());

 }

}

5.隨機生成和統計初步

package apache.commons.math.test;

import org.apache.commons.math3.random.RandomDataGenerator;
import org.apache.commons.math3.stat.Frequency;
import org.apache.commons.math3.stat.StatUtils;

/**
 *
 * @ClassName: RandomTest
 * @Description: 隨機生成和統計初步
 * @author zengfh
 * @date 2014年11月21日 下午2:23:04
 *
 */
public class RandomTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  random();
 }

 private static void random() {
  // TODO Auto-generated method stub
  RandomDataGenerator randomData = new RandomDataGenerator();

  // Generate a random int value uniformly distributed between lower and
  // upper, inclusive
  System.out.println("a uniform value: " + randomData.nextInt(1, 6));
  // Returns a random value from an Exponential distribution with the
  // given mean
  System.out.println("a Exponential value: "
    + randomData.nextExponential(5));
  // Generate a random value from a Normal
  System.out.println("a Normal value: " + randomData.nextGaussian(0, 1));
  // Generates a random value from the Poisson distribution with the given
  // mean
  System.out.println("a Poisson value: " + randomData.nextPoisson(3));
  // Generates an integer array of length k whose entries are selected
  // randomly, without repetition, from the integers 0 through n-1
  int[] a = randomData.nextPermutation(10, 3);
  for (int i = 0; i < a.length; i++) {
   System.out.print(a[i] + " ");
  }
  System.out.println();

  // generate 1000 numbers between 0 and 3 inclusive, then using frequency
  // to see the distribution

  Frequency freq = new Frequency();
  int value = 0;
  for (int i = 0; i < 1000; i++) {
   value = randomData.nextInt(0, 3);
   freq.addValue(value);
  }
  long[] observed = new long[4];
  double[] perc = new double[4];
  for (int i = 0; i < 4; i++) {
   observed[i] = freq.getCount(i);
   perc[i] = freq.getPct(i);
   System.out.println("there are " + observed[i] + " " + i
     + " in dataset with " + (perc[i] * 100) + "%");
  }

  // stat test
  double[] data = { 1d, 2d, 2d, 3d };
  System.out.println("sum of data is " + StatUtils.sum(data));
  System.out.println("sum of square of data is " + StatUtils.sumSq(data));
  System.out.println("var of data is " + StatUtils.variance(data));
  System.out.println("mean of data is " + StatUtils.mean(data));
  System.out.println("max value of data is " + StatUtils.max(data));
  System.out.println("min value of data is " + StatUtils.min(data));
  System.out.println("geometry mean of data is "
    + StatUtils.geometricMean(data));
  System.out.println("product of data is " + StatUtils.product(data));
 }

}

6.聚類和回歸

package apache.commons.math.test;

import org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression;
import org.apache.commons.math3.stat.regression.SimpleRegression;

/**
 *
 * @ClassName: RegressionTest
 * @Description: 聚類和回歸
 * @author zengfh
 * @date 2014年11月21日 下午1:56:19
 *
 */
public class RegressionTest {
    /**
    * @param args
    */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        regression();
        System.out.println("-------------------------------------");
        simple();
    }

    private static void simple() {
        // TODO Auto-generated method stub
        double[][] data = { { 0.1, 0.2 }, {338.8, 337.4 }, {118.1, 118.2 },
                {888.0, 884.6 }, {9.2, 10.1 }, {228.1, 226.5 }, {668.5, 666.3 }, {998.5, 996.3 },
                {449.1, 448.6 }, {778.9, 777.0 }, {559.2, 558.2 }, {0.3, 0.4 }, {0.1, 0.6 }, {778.1, 775.5 },
                {668.8, 666.9 }, {339.3, 338.0 }, {448.9, 447.5 }, {10.8, 11.6 }, {557.7, 556.0 },
                {228.3, 228.1 }, {998.0, 995.8 }, {888.8, 887.6 }, {119.6, 120.2 }, {0.3, 0.3 },
                {0.6, 0.3 }, {557.6, 556.8 }, {339.3, 339.1 }, {888.0, 887.2 }, {998.5, 999.0 },
                {778.9, 779.0 }, {10.2, 11.1 }, {117.6, 118.3 }, {228.9, 229.2 }, {668.4, 669.1 },
                {449.2, 448.9 }, {0.2, 0.5 }
        };
        SimpleRegression regression = new SimpleRegression();
        for (int i = 0; i < data.length; i++) {
            regression.addData(data[i][1], data[i][0]);
        }
        System.out.println("slope is "+regression.getSlope());
        System.out.println("slope std err is "+regression.getSlopeStdErr());
        System.out.println("number of observations is "+regression.getN());
        System.out.println("intercept is "+regression.getIntercept());
        System.out.println("std err intercept is "+regression.getInterceptStdErr());
        System.out.println("r-square is "+regression.getRSquare());
        System.out.println("SSR is "+regression.getRegressionSumSquares());
        System.out.println("MSE is "+regression.getMeanSquareError());
        System.out.println("SSE is "+regression.getSumSquaredErrors());
        System.out.println("predict(0) is "+regression.predict(0));
        System.out.println("predict(1) is "+regression.predict(1));
    }

    private static void regression() {
        // TODO Auto-generated method stub
        double[] y;
        double[][] x;
        y = new double[]{11.0, 12.0, 13.0, 14.0, 15.0, 16.0};
        x = new double[6][];
        x[0] = new double[]{1.0, 0, 0, 0, 0, 0};
        x[1] = new double[]{1.0, 2.0, 0, 0, 0, 0};
        x[2] = new double[]{1.0, 0, 3.0, 0, 0, 0};
        x[3] = new double[]{1.0, 0, 0, 4.0, 0, 0};
        x[4] = new double[]{1.0, 0, 0, 0, 5.0, 0};
        x[5] = new double[]{1.0, 0, 0, 0, 0, 6.0};
        System.out.println(x[0].length+"-----------");
        OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression();
        regression.newSampleData(y, x);     
        double[] betaHat = regression.estimateRegressionParameters();
        System.out.println("Estimates the regression parameters b:");
        print(betaHat);
        double[] residuals = regression.estimateResiduals();
        System.out.println("Estimates the residuals, ie u = y - X*b:");
        print(residuals);
        double vary = regression.estimateRegressandVariance();
        System.out.println("Returns the variance of the regressand Var(y):");
        System.out.println(vary);
        double[] erros = regression.estimateRegressionParametersStandardErrors();
        System.out.println("Returns the standard errors of the regression parameters:");
        print(erros);
        double[][] varb = regression.estimateRegressionParametersVariance();
    }

    private static void print(double[] v) {
        // TODO Auto-generated method stub
        for(int i=0;i<v.length;i++){
            System.out.print(v[i]+ " ");
        }
        System.out.println();
    }

}

7.math組件用法實例

package apache.commons.math.test;

import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.LUDecomposition;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.stat.descriptive.moment.GeometricMean;
import org.apache.commons.math3.stat.descriptive.moment.Kurtosis;
import org.apache.commons.math3.stat.descriptive.moment.Mean;
import org.apache.commons.math3.stat.descriptive.moment.Skewness;
import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation;
import org.apache.commons.math3.stat.descriptive.moment.Variance;
import org.apache.commons.math3.stat.descriptive.rank.Max;
import org.apache.commons.math3.stat.descriptive.rank.Min;
import org.apache.commons.math3.stat.descriptive.rank.Percentile;
import org.apache.commons.math3.stat.descriptive.summary.Product;
import org.apache.commons.math3.stat.descriptive.summary.Sum;
import org.apache.commons.math3.stat.descriptive.summary.SumOfSquares;

/**
 *
 * @ClassName: TestMathUserage
 * @Description: math組件用法實例
 * @author zengfh
 * @date 2014年11月21日 下午1:25:24
 *
 */
public class TestMathUserage {
 public static void main(String[] args) {
  double[] values = new double[] { 0.33, 1.33, 0.27333, 0.3, 0.501,
    0.444, 0.44, 0.34496, 0.33, 0.3, 0.292, 0.667 };
  /*
  * System.out.println( "min: " + StatUtils.min( values ) );
  * System.out.println( "max: " + StatUtils.max( values ) );
  * System.out.println( "mean: " + StatUtils.mean( values ) ); // Returns
  * the arithmetic mean of the entries in the input array, or Double.NaN
  * if the array is empty System.out.println( "product: " +
  * StatUtils.product( values ) ); //Returns the product of the entries
  * in the input array, or Double.NaN if the array is empty.
  * System.out.println( "sum: " + StatUtils.sum( values ) ); //Returns
  * the sum of the values in the input array, or Double.NaN if the array
  * is empty. System.out.println( "variance: " + StatUtils.variance(
  * values ) ); // Returns the variance of the entries in the input
  * array, or Double.NaN if the array is empty.
  */

  Min min = new Min();
  Max max = new Max();
 
  Mean mean = new Mean(); // 算術平均值
  Product product = new Product();//乘積
  Sum sum = new Sum();
  Variance variance = new Variance();//方差
  System.out.println("min: " + min.evaluate(values));
  System.out.println("max: " + max.evaluate(values));
  System.out.println("mean: " + mean.evaluate(values));
  System.out.println("product: " + product.evaluate(values));
  System.out.println("sum: " + sum.evaluate(values));
  System.out.println("variance: " + variance.evaluate(values));

  Percentile percentile = new Percentile(); // 百分位數
  GeometricMean geoMean = new GeometricMean(); // 幾何平均數,n個正數的連乘積的n次算術根叫做這n個數的幾何平均數
  Skewness skewness = new Skewness(); // Skewness();
  Kurtosis kurtosis = new Kurtosis(); // Kurtosis,峰度
  SumOfSquares sumOfSquares = new SumOfSquares(); // 平方和
  StandardDeviation StandardDeviation = new StandardDeviation();//標准差
  System.out.println("80 percentile value: "
    + percentile.evaluate(values, 80.0));
  System.out.println("geometric mean: " + geoMean.evaluate(values));
  System.out.println("skewness: " + skewness.evaluate(values));
  System.out.println("kurtosis: " + kurtosis.evaluate(values));
  System.out.println("sumOfSquares: " + sumOfSquares.evaluate(values));
  System.out.println("StandardDeviation: " + StandardDeviation.evaluate(values));
 
  System.out.println("-------------------------------------");
  // Create a real matrix with two rows and three columns
  double[][] matrixData = { {1d,2d,3d}, {2d,5d,3d}};
  RealMatrix m = new Array2DRowRealMatrix(matrixData);
  System.out.println(m);
  // One more with three rows, two columns
  double[][] matrixData2 = { {1d,2d}, {2d,5d}, {1d, 7d}};
  RealMatrix n = new Array2DRowRealMatrix(matrixData2); 
  // Note: The constructor copies  the input double[][] array. 
  // Now multiply m by n
  RealMatrix p = m.multiply(n);
  System.out.println("p:"+p);
  System.out.println(p.getRowDimension());    // 2
  System.out.println(p.getColumnDimension()); // 2 
  // Invert p, using LU decomposition
  RealMatrix pInverse = new LUDecomposition(p).getSolver().getInverse();
  System.out.println(pInverse);
 }
}

Commons Math 的詳細介紹:請點這裡
Commons Math 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved