Fitting noisy curves, sine functions with polynomials

Linear function fit to linear noise

Program content: First generate a linear scatter image with random noise, set a first-order polynomial to fit the scatter image, and finally display the original scatter image and the fitted polynomial function.

code show as below:

import numpy as np
import matplotlib.pyplot as plt
from numpy import polyfit

x = np.linspace(-5, 5, 100)
y = 4 * x + 1.5
noise_y = y + np.random.randn(y.shape[0]) * 2.5
plt.subplot(2,1,1)
plt.title("original image")
p = plt.plot(x, noise_y,'rx', marker="3")

plt.subplot(2,1,2)
# 用多项式进行拟合,在此用一次函数拟合
coeff = polyfit(x, noise_y, 1)
print(coeff)
plt.title("image after polynomial fitting")
p = plt.plot(x, coeff[0] * x + coeff[1], 'k-')
plt.show()

The result display:
insert image description here

Fitting a sine function with a polynomial

Here, three-degree polynomials, five-degree polynomials and nine-degree polynomials are used to fit the sine function.

The program code is as follows:

import numpy as np
import matplotlib.pyplot as plt
from numpy import polyfit, poly1d

x = np.linspace(0,4*np.pi,200)
y = np.sin(x)
y3 = poly1d(polyfit(x,y,3))
y5 = poly1d(polyfit(x,y,5))
y9 = poly1d(polyfit(x,y,9))

plt.subplot(2,2,1)
plt.title("original image")
p = plt.plot(x, y)
plt.subplot(2,2,2)
plt.title("Third Order polynomials")
p = plt.plot(x, y3(x))
plt.subplot(2,2,3)
plt.title("fifth Order polynomials")
p = plt.plot(x, y5(x))
plt.subplot(2,2,4)
plt.title("ninth Order polynomials")
p = plt.plot(x, y9(x))
plt.show()

The obtained results are shown as follows: As
insert image description here
can be seen from the figure, as the polynomial coefficient increases, the fitting effect is getting better and better. When the polynomial is 9, the sine function can be restored very well.

Guess you like

Origin blog.csdn.net/ximu__l/article/details/129354159