なんとなくC言語の勉強を行いました。
以下線形回帰の実装例です。
(linear_regression.c という名前で保存します)
コード
#include <stdio.h> int main(void) { double x[] = {1, 2, 3, 4, 5}; double y[] = {2, 4, 5, 4, 5}; int n = 5; double sum_x=0, sum_y=0, sum_xy=0, sum_x2=0; for (int i = 0; i < n; i++) { sum_x += x[i]; sum_y += y[i]; sum_xy += x[i] * y[i]; sum_x2 += x[i] * x[i]; } double slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x * sum_x); double intercept = (sum_y - slope * sum_x) / n; printf("y = %.2fx + %.2f\n", slope, intercept); return 0; }
コンパイル
gcc linear_regression.c -o linear_regression
実行
./linear_regression