1
0
harvensine-compute/fit_curve.py

31 lines
654 B
Python

import numpy as np
from scipy.optimize import curve_fit
from matplotlib import pyplot as plt
import math
x = np.linspace(0, math.pi / 2, num=1000)
y = np.sin(x)
def test(x, a, b, c, d, e, f):
return a * x**6 + b * x**5 + c * x**4 + d * x**3 + e * x**2 + f * x
param, param_cov = curve_fit(test, x, y)
print("Sine function coefficients:")
print(*param)
# ans stores the new y-data according to
# the coefficients given by curve-fit() function
ans = test(x, *param)
print("Max error:")
print(abs(y-ans).max())
plt.plot(x, y, 'o', color='red', label="data")
plt.plot(x, ans, '--', color='blue', label="optimized data")
plt.legend()
plt.show()