一元线性方程python
时间: 2023-11-01 20:00:40 浏览: 186
python解一元方程
一元线性方程python代码如下:
```python
import numpy as np
def linear_regression(X, y):
n = len(X)
mean_X = np.mean(X)
mean_y = np.mean(y)
lxx = np.sum((X - mean_X) ** 2)
lxy = np.sum((X - mean_X) * (y - mean_y))
b = lxy / lxx
a = mean_y - b * mean_X
return a, b
X = np.array([6, 8, 10, 14, 18])
y = np.array([7, 9, 13, 17.5, 18])
a, b = linear_regression(X, y)
print("一元线性回归方程为:y = {:.2f} + {:.2f}x".format(a, b))
```
阅读全文