本文實例講述了Java實現的n階曲線擬合功能。分享給大家供大家參考,具體如下:
前面一篇文章Java實現求解一元n次多項式的方法,能解多項式以后,還需要利用那個類,根據若干采樣點數據來對未來數據進行預測,擬合的矩陣在上一篇文章中已經貼出來了,這里就不說了,本篇主要是如何根據采樣點來計算系數矩陣,并計算預測點的值。
原理很簡單,公式在上一篇文章中也有了,此處直接貼代碼。
其中用到了上一篇文章中寫的類commonAlgorithm.PolynomiaSoluter
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
|
package commonAlgorithm; import commonAlgorithm.PolynomialSoluter; import java.lang.Math; public class LeastSquare { private double [][] matrixA; private double [] arrayB; private double [] factors; private int order; public LeastSquare() { } /* * 實例化后,計算前,先要輸入參數并生成公式 arrayX為采樣點的x軸坐標,按照采樣順序排列 * arrayY為采樣點的y軸坐標,按照采樣順序與x一一對應排列 order * 為進行擬合的階數。用低階來擬合高階曲線時可能會不準確,但階數過高會導致計算緩慢 */ public boolean generateFormula( double [] arrayX, double [] arrayY, int order) { if (arrayX.length != arrayY.length) return false ; this .order = order; int len = arrayX.length; // 擬合運算中的x矩陣和y矩陣 matrixA = new double [order + 1 ][order + 1 ]; arrayB = new double [order + 1 ]; // 生成y矩陣以及x矩陣中冪<=order的部分 for ( int i = 0 ; i < order + 1 ; i++) { double sumX = 0 ; for ( int j = 0 ; j < len; j++) { double tmp = Math.pow(arrayX[j], i); sumX += tmp; arrayB[i] += tmp * arrayY[j]; } for ( int j = 0 ; j <= i; j++) matrixA[j][i - j] = sumX; } // 生成x矩陣中冪>order的部分 for ( int i = order + 1 ; i <= order * 2 ; i++) { double sumX = 0 ; for ( int j = 0 ; j < len; j++) sumX += Math.pow(arrayX[j], i); for ( int j = i - order; j < order + 1 ; j++) { matrixA[i - j][j] = sumX; } } // 實例化PolynomiaSoluter并解方程組,得到各階的系數序列factors PolynomialSoluter soluter = new PolynomialSoluter(); factors = soluter.getResult(matrixA, arrayB); if (factors == null ) return false ; else return true ; } // 根據輸入坐標,以及系數序列factors計算指定坐標的結果 public double calculate( double x) { double result = factors[ 0 ]; for ( int i = 1 ; i <= order; i++) result += factors[i] * Math.pow(x, i); return result; } } |
希望本文所述對大家java程序設計有所幫助。
原文鏈接:http://blog.csdn.net/strangerzz/article/details/45250063