利用Java实现部分科学计算函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import java.math.MathContext;
/**
* Created by Noah on 16/6/12.
*/
public class MathUtil {
//求最小值
static double getMin(double[] input){
double min = 10;
int len = input.length;
for (int i=0;i<input.length;i++){
if (input[i]<min){
min=input[i];
}
}
return min;
}
//求最大值
static double getMax(double[] input){
double max = -10;
int len = input.length;
for (int i=0;i<len;i++){
if (input[i]>max){
max=input[i];
}
}
return max;
}
//求和
static double getSum(double[] input){
double sum=0;
int len = input.length;
for (int i=0;i<len;i++){
sum+=input[i];
}
return sum;
}
//求平均数
static double getAverage(double[] input){
double sum = getSum(input);
return sum/input.length;
}
//平方和
public static double getSquareSum(double[] inputData) {
if (inputData == null || inputData.length == 0)
return -1;
int len = inputData.length;
double sqrsum = 0.0;
for (int i = 0; i < len; i++) {
sqrsum = sqrsum + inputData[i] * inputData[i];
}
return sqrsum;
}
//求方差
public static double getVariance(double[] inputData) {
int count = inputData.length;
double sqrsum = getSquareSum(inputData);
double average = getAverage(inputData);
double result;
result = (sqrsum - count * average * average) / count;
return result;
}
//求偏值与峰度
public static double[] getKS(double[] inputData){
double[] output={0.0,0.0};
double average = getAverage(inputData);
double m2 = 0.0;
double m3 = 0.0;
double m4 = 0.0;
int len = inputData.length;
for (int i=0;i<len;i++){
m2 = m2 + Math.pow(inputData[i],2);
m3 = m3 + Math.pow(inputData[i],3);
m4= m4 + Math.pow(inputData[i],4);
}
output[0] = len * m4 / Math.pow(m2,2);
output[1] = Math.pow(len,-0.5) * m3 / Math.pow(m2,1.5);
return output;
}
//求相关系数
public static double cor(double[] x,double[] y){
double sumX = getSum(x);
double sumY = getSum(y);
double sumX_Sq = getSquareSum(x);
double sumY_Sq = getSquareSum(y);
double sumXY = 0.0;
int len = x.length;
for (int i =0; i <len;i++) {
sumXY += x[i] * y[i];
}
double numerator = sumXY - sumX * sumY / len;
double denominator = Math.sqrt((sumX_Sq - sumX * sumX / len) * (sumY_Sq - sumY * sumY / len));
if (denominator == 0) {
return 0;
}
return numerator / denominator;
}
}