gunshi-project-ss/src/main/java/com/gunshi/project/hsz/model/RegressionEquation.java

107 lines
2.6 KiB
Java
Raw Normal View History

package com.gunshi.project.hsz.model;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
* 线
*/
@Data
public class RegressionEquation {
/**
*
*/
private int order;
/**
*
* y = ax² + bx + ccoefficients = [c, b, a]
*/
private List<BigDecimal> coefficients;
/**
* R²
*/
private BigDecimal rSquared;
/**
*
*/
private int dataCount;
/**
*
*/
private String equationString;
public RegressionEquation(int order, List<BigDecimal> coefficients, BigDecimal rSquared, int dataCount) {
this.order = order;
this.coefficients = coefficients;
this.rSquared = rSquared;
this.dataCount = dataCount;
this.equationString = generateEquationString();
}
/**
*
*/
private String generateEquationString() {
StringBuilder sb = new StringBuilder("y = ");
for (int i = coefficients.size() - 1; i >= 0; i--) {
BigDecimal coeff = coefficients.get(i);
if (coeff.compareTo(BigDecimal.ZERO) == 0) {
continue;
}
// 符号处理
if (sb.length() > 4 && coeff.compareTo(BigDecimal.ZERO) > 0) {
sb.append(" + ");
} else if (sb.length() > 4 && coeff.compareTo(BigDecimal.ZERO) < 0) {
sb.append(" - ");
coeff = coeff.abs();
}
// 系数和变量
if (i == 0) {
// 常数项
sb.append(String.format("%.4f", coeff));
} else {
// 非常数项
if (coeff.compareTo(BigDecimal.ONE) != 0 && coeff.compareTo(BigDecimal.ONE.negate()) != 0) {
sb.append(String.format("%.4f", coeff));
}
sb.append("x");
if (i > 1) {
sb.append("^").append(i);
}
}
}
return sb.toString();
}
/**
* xy
*/
public BigDecimal predict(BigDecimal x) {
BigDecimal result = BigDecimal.ZERO;
BigDecimal xPower = BigDecimal.ONE;
for (int i = 0; i < coefficients.size(); i++) {
result = result.add(coefficients.get(i).multiply(xPower));
xPower = xPower.multiply(x);
}
return result;
}
@Override
public String toString() {
return String.format("%s", equationString);
}
}