Java 使用拟合曲线示例代码
时间: 2024-01-26 07:03:29 浏览: 15
以下是使用Java实现拟合曲线的示例代码:
```java
import org.apache.commons.math3.fitting.PolynomialCurveFitter;
import org.apache.commons.math3.fitting.WeightedObservedPoints;
public class CurveFitter {
public static void main(String[] args) {
// Define the data points
WeightedObservedPoints data = new WeightedObservedPoints();
data.add(1, 2);
data.add(2, 5);
data.add(3, 10);
data.add(4, 17);
data.add(5, 26);
// Define the degree of the polynomial
int degree = 2;
// Fit the polynomial to the data points
PolynomialCurveFitter fitter = PolynomialCurveFitter.create(degree);
double[] coefficients = fitter.fit(data.toList());
// Print the coefficients of the polynomial
System.out.println("The coefficients of the polynomial are:");
for (double coefficient : coefficients) {
System.out.println(coefficient);
}
}
}
```
这个示例代码使用了 Apache Commons Math 库来实现拟合曲线。它首先定义了一组数据点,然后指定了要拟合的多项式的次数(在这个例子中是二次方程)。接下来,它创建了一个 PolynomialCurveFitter 对象,使用 fit() 方法来拟合多项式,然后打印出多项式的系数。