Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java source code to solve approximate equation with least squares method.
/**************************************
最小二乗法 ( LeastSquaresMethod.java )
**************************************/
/*
* 計算クラス
*/
class Calc {
// 定数定義
static final byte N = 7; // データ数
static final byte M = 5; // 予測曲線の次数
static final double X[] = {-3, -2, -1, 0, 1, 2, 3}; // 測定データ x
static final double Y[] = { 5, -2, -3, -1, 1, 4, 5}; // 測定データ y
// 変数宣言
double s[] = new double[2 * M + 1];
double t[] = new double[M + 1];
double a[][] = new double[M + 1][M + 2];
// コンストラクタ
Calc() {
// s[] 初期化
for (int i = 0; i <= 2 * M; i++)
s[i] = 0;
// t[] 初期化
for (int i = 0; i <= M; i++)
t[i] = 0;
}
// 最小二乗法
void calcLeastSquaresMethod() {
try {
// s[], t[] 計算
calcST();
// a[][] に s[], t[] 代入
insST();
// 掃き出し
sweepOut();
} catch(Exception e) {
e.printStackTrace();
}
}
// s[], t[] 計算
private void calcST() {
for (int i = 0; i < N; i++) {
for (int j = 0; j <= 2 * M; j++)
s[j] += Math.pow(X[i], j);
for (int j = 0; j <= M; j++)
t[j] += Math.pow(X[i], j) * Y[i];
}
}
// a[][] に s[], t[] 代入
private void insST() {
for (int i = 0; i <= M; i++) {
for (int j = 0; j <= M; j++)
a[i][j] = s[i + j];
a[i][M + 1] = t[i];
}
}
// 掃き出し
private void sweepOut() {
for (int k = 0; k <= M; k++) {
double p = a[k][k];
for (int j = k; j <= M + 1; j++)
a[k][j] /= p;
for (int i = 0; i <= M; i++) {
if (i != k) {
double d = a[i][k];
for (int j = k; j <= M + 1; j++)
a[i][j] -= d * a[k][j];
}
}
}
}
// y 値計算&結果出力
void display() {
try {
for (int k = 0; k <= M; k++)
System.out.printf("a%d = %10.6f\n", k, a[k][M + 1]);
System.out.println(" x y");
for (double px = -3; px <= 3; px += .5) {
double p = 0;
for (int k = 0; k <= M; k++)
p += a[k][M + 1] * Math.pow(px, k);
System.out.printf("%5.1f%5.1f\n", px, p);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
/*
* メイン
*/
class LeastSquaresMethod {
public static void main (String[] args) {
Calc obj = new Calc();
try {
// 最小二乗法計算
obj.calcLeastSquaresMethod();
// 結果出力
obj.display();
} catch(Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment