1、使用方法
import com.gfkd.yfaps.util.CurveFittingUtil;
public class testCurveFittingUtil {
//用来生成数据
static double y(double x)
{
return 5+4*x+3*x*x+2*x*x*x;//代表公式:y=5+4*x+3*(x^2)+2*(x^3)
}
public static void main(String[] args) {
//建立曲线拟合工具类的对象
CurveFittingUtil util=new CurveFittingUtil(3);
//调用添加数据点方法
for (int i=1;i<1000;i++)
util.add(i,y(i));//根据预期函数生成一些数据,真正使用时直接将真实数据一个个添加进去即可
//输出拟合出的二项式
System.out.println("文本形式结果:");
System.out.println(util.getTextStringFormula());//文本形式
System.out.println("网页形式结果:");
System.out.println(util.getHtmlStringFormula());//网页形式
System.out.println("输出每个系数:");
for (double d:util.getCoeffient())
System.out.print(d+" ");
}
}
执行结果:
网页代码显示效果:
y=4.999999984929429+4.000000000227827*X1+2.999999999999302*X2+2.0000000000000004*X3
工具源码:
package com.gfkd.yfaps.util;
import org.apache.commons.math3.fitting.PolynomialCurveFitter;
import org.apache.commons.math3.fitting.WeightedObservedPoints;
/**
* @Description: 曲线拟合工具
* @Author: 陈福星
* @Date: 2020/6/27
*/
public class CurveFittingUtil {
private int degree;
private WeightedObservedPoints obs = new WeightedObservedPoints();
private PolynomialCurveFitter fitter ;
/**
* 创建一个几阶的多项式来模拟曲线
* @param degree
*/
public CurveFittingUtil(int degree)
{
fitter = PolynomialCurveFitter.create(degree);
this.degree=degree;
}
/**
* 增加数据点
* @param x
* @param y
*/
public void add(double x,double y)
{
obs.add(x,y);
}
/**
* 清空数据点
*/
public void clear()
{
obs.clear();
}
public String getHtmlStringFormula()
{
StringBuilder sb=new StringBuilder("y=");
double[] coef=fitter.fit(obs.toList());
sb.append(coef[0]);
if (coef[1]>0)
sb.append("+");
for (int i=1;i<coef.length;i++)
{
if (coef[i]>0&&sb.charAt(sb.length()-1)!='+')
sb.append("+");
sb.append(coef[i]+"*"+ htmlPowerString(i));
}
return sb.toString();
}
public String getTextStringFormula()
{
StringBuilder sb=new StringBuilder("y=");
double[] coef=fitter.fit(obs.toList());
sb.append(coef[0]);
if (coef[1]>0)
sb.append("+");
for (int i=1;i<coef.length;i++)
{
if (coef[i]>0&&sb.charAt(sb.length()-1)!='+')
sb.append("+");
sb.append(coef[i]+"*"+ textPowerString(i));
}
return sb.toString();
}
/**
* 生成幂的字符串(html显示成幂 10<span style="vertical-align:super">9</span>)
* @param y:幂y
* @return
*/
public String htmlPowerString(int y)
{
return "X<span style=\"vertical-align:super\">"+y+"</span>";
}
public String textPowerString(int y)
{
return "(X^"+y+")";
}
/**
* 将拟合后的曲线的从x^0到x^degree的系数输出
* 例如dggree=3 返回的系数为[3,5,7]则多项式为y=3+5*X+7*X^2
* @return double[]
*/
public double[] getCoeffient()
{
return fitter.fit(obs.toList());
}
}