目录
1、最小二乘法拟合直线
2、需要用到的公式
3、计算各个参数 ,得到函数表达式
4、可视化-绘画图像
1、最小二乘法拟合直线
double x[15] = {29,34,39,44,49,54,59,64,69,74,79,84,89,94,99};
double y[15] = { 0.2989,0.3036,0.3084,0.3133,0.3182,0.3231,0.3284,
0.3331,0.3380,0.3429,0.3478,0.3527,0.3577,0.3626,0.3677 };
x --> t('c) ,y-->i(mA)
T=273+t ,mA=100uA
x --> T(K) ,y-->i(uA)
做出i-T图像,利用最小二乘法拟合直线
y=a+bx
2、需要用到的公式
r为相关系数
3、计算各个参数 ,得到函数表达式
#include<iostream>
#include<cmath>
using namespace std;
int main() {
double x[15] = {29,34,39,44,49,54,59,64,69,74,79,84,89,94,99};
double y[15] = { 0.2989,0.3036,0.3084,0.3133,0.3182,0.3231,0.3284,
0.3331,0.3380,0.3429,0.3478,0.3527,0.3577,0.3626,0.3677 };
for (int i = 0; i < 15; i++) {
y[i] *= 1000;
x[i] += 273;
}
double t1 = 0;
double t2 = 0;
for (int i = 0; i < 15; i++) {
t1 += x[i];
t2 += y[i];
}
double aver_x = t1 / 15;
double aver_y = t2 / 15;
cout << "aver_x = " << aver_x << endl;
cout << "aver_y = " << aver_y << endl;
double b, a,r;
double sum1 = 0;
double sum2 = 0;
double sum3 = 0;
for (int i = 0; i < 15; i++) {
sum1 += (x[i] - aver_x) * (y[i] - aver_y);
sum2 += (x[i] - aver_x) * (x[i] - aver_x);
sum3 += (y[i] - aver_y) * (y[i] - aver_y);
}
b = sum1 / sum2;
a = aver_y - b * aver_x;
r = sum1 / (sqrt(sum2) * sqrt(sum3));
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "r = " << r << endl;
}
4、可视化-绘画图像
# -*- coding: utf-8 -*-
import numpy as np
# 假设我们有一组数据点
x_data = np.array([302,307,312,317,322,327,332,337,342,347,352,357,362,367,372])
y_data = np.array([298.9,303.6,308.4,313.3,318.2,323.1,328.4,333.1,
338,342.9,347.8,352.7,357.7,362.6,367.7,])
# 为了使用最小二乘法,我们需要构建设计矩阵X
# 在这个例子中,我们有一个截距项和一个斜率项
X = np.vstack([np.ones(len(x_data)), x_data]).T
# 使用NumPy的linalg.lstsq函数来执行最小二乘法
# 这个函数返回四个值:系数、残差、秩和s
coefficients, residuals, rank, s = np.linalg.lstsq(X, y_data, rcond=None)
# 系数数组中的第一个元素是截距,第二个元素是斜率
intercept = coefficients[0]
slope = coefficients[1]
print("Intercept:", intercept)
print("Slope:", slope)
# 使用求得的斜率和截距来生成拟合直线
y_fit = intercept + slope * x_data
# 打印拟合结果
print("Fitted values:", y_fit)
# 可视化原始数据点和拟合直线
import matplotlib.pyplot as plt
plt.scatter(x_data, y_data, label='Original data')
plt.plot(x_data, y_fit, color='red', label='Fitted line')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()