java实现T检验(Ttest)
最近公司将matlab中的算法要搬到java中来展示,本篇将向你展示如何不去调用matlab,纯用java来计算T检验。此代码算出结果与matlab、excel、的计算逻辑相同,自然结果也相同。
在编写此代码之前,我找过在线计算的网站,发现于matlab的计算结果不同,且差距较大,应该是计算逻辑不同。
前提需要引入maven依赖,apach的math3公共计算包,包括各种各样的计算
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-math3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
以下为代码片段:
package success;
import org.apache.commons.math3.distribution.TDistribution;
import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation;
public class TtestDemo {
public static void main(String[] args) {
double[] x= {119, 114, 126, 98, 75, 93, 125, 103, 91, 98, 90, 108, 91, 122, 110, 103, 148, 81, 83, 113, 86, 120, 81, 102, 86, 80, 107, 87, 93, 91};
double[] y= {130, 148, 156, 126, 110, 120, 151, 135, 111, 112, 140, 143, 120, 143, 138, 129, 173, 122, 100, 158, 117, 140, 107, 130, 129, 109, 139, 108, 125, 129};
TtestDemo t = new TtestDemo();
double t1 = t.getT(x, y);
System.out.println(t1);
double p = t.getP(x, y);
System.out.println(p);
}
/**
* 拿到T值
* @param x
* @param y
* @return
*/
public double getT(double x[],double y[]){
double a = getMean(x)-getMean(y);
double b = getStandardDeviation(x,y);
double c = Math.sqrt(x.length);
double v = a / (b /c);
return v;
}
/**
* 计算列平均
* @param array
* @return
*/
public double getMean(double[] array) {
int n=array.length;
double sum=0;
for (double d : array) {
sum=sum+d;
}
return sum/n;
}
/**
* 计算标准偏差
* @param x
* @param y
* @return
*/
public double getStandardDeviation (double[] x,double[] y){
double[] z =new double[x.length];
for(int i=0;i<x.length;i++){
z[i]=x[i]-y[i];
}
StandardDeviation standardDeviation =new StandardDeviation();
double evaluate = standardDeviation.evaluate(z);
return evaluate;
}
/**
* 得到P值
* @param x
* @param y
* @return
*/
public double getP(double [] x, double [] y) {
int free = x.length-1;
double t= getT(x, y);
TDistribution td=new TDistribution(free);
double cumulative = td.cumulativeProbability(t);
double p;
if(t>0) {
p=(1-cumulative)*2;
}else {
p=cumulative*2;
}
return p;
}
}