一元最小二乘法(c语言实现)
Posted _WILLPOWER_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一元最小二乘法(c语言实现)相关的知识,希望对你有一定的参考价值。
文章目录
一元最小二乘法
🍺
#include <stdio.h>
typedef unsigned int uint;
char filename[] = ".\\\\data.csv";
char str[30];
uint x[50];
uint y[50];
void LeastSquare(uint *x, uint *y, uint lenth, double *a, double *b)
double sum_x2 = 0, sum_y = 0, sum_x = 0, sum_xy = 0;
for(int i=0; i< lenth; ++i)
sum_x2 += x[i]*x[i];
sum_x += x[i];
sum_xy += x[i]*y[i];
sum_y += y[i];
*a = (sum_xy*lenth - sum_x*sum_y) / (sum_x2*lenth - sum_x*sum_x);
*b = (sum_x2*sum_y - sum_x*sum_xy) /(sum_x2 * lenth - sum_x*sum_x);
int main()
FILE *fp = fopen(filename,"r");
uint i = 0;
double a, b;
fgets(str,30,fp);
fputs(str,stdout);
while(1)
if(fscanf(fp,"%u,%u",&x[i],&y[i]) != EOF)
printf("%u,%u\\r\\n",x[i],y[i]);
i++;
else
break;
fclose(fp);
LeastSquare(x, y, 50, &a, &b);
printf("a is %.2f, b is %.2f", a, b);
return 0;
python画图验证
🐍
#%%
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
#%%
data = pd.read_csv("./data.csv")
#%%
data.set_index('BOD5',inplace=True)
data = data.sort_index()
#%%
a = 1.924705
b = 76.195741
x1 = np.array(data.index)
y1 = a*x1+b
#%%
data['fitline'] = y1
data.plot()
# data.sort_index().plot()
# %%
plt.plot(x1,y1)
plt.show()
# %%
效果图
数据集
📖
BOD5,CODCr
375 ,809
341 ,734
258 ,559
614 ,1199
597 ,1184
469 ,989
458 ,981
398 ,855
357 ,768
323 ,699
478 ,984
412 ,882
387 ,829
365 ,785
256 ,554
298 ,642
287 ,620
285 ,616
244 ,529
289 ,613
369 ,793
358 ,770
348 ,749
411 ,881
402,864
399 ,857
357 ,768
362 ,789
342 ,763
289 ,624
287 ,619
268 ,579
322 ,694
411 ,845
325 ,701
347 ,777
356 ,766
329 ,709
298 ,643
276 ,596
258 ,559
298 ,643
249 ,539
246 ,544
348 ,749
368 ,791
384 ,826
410 ,880
458 ,998
388,834
以上是关于一元最小二乘法(c语言实现)的主要内容,如果未能解决你的问题,请参考以下文章