Creating a quadratic fit on random data

import numpy as np
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
from numpy.random import default_rng

Creating a quadratic fit on random data#

In this notebook, you will

  • build a variable of fabricated falling heights, y = \(\frac{g}{2}t^2 + error\)

  • find the best-fit quadratic function with np.polyfit

  • plot the data and fit using poly1d

rng = default_rng()
x = np.linspace(0,5)
y = 9.81/2*x**2 + (rng.random(len(x)) - 0.5)*4

plt.plot(x, y)
[<matplotlib.lines.Line2D at 0x7f38809ccbb0>]
../_images/292222e26311271429d0d68e9d306ba79c78be621176bee279b9ec7f6e67beb7.png

Above, the fabricated falling data is shown for 5 seconds. The error is introduced as uniformly random numbers from -2 - 2 as (rng.random(len(x) - 0.5)*4.

Next, you build the polynomial fit with np.polyfit. Finally, plug the polynomial constants into the np.poly1d function to created a function for \(y_{fit}(x)\) = pp(x).

A = np.polyfit(x, y, 2)
pp = np.poly1d(A)
plt.plot(x, y,'o', label = 'data')
plt.plot(x, pp(x), label = 'quadratic fit')
plt.legend();
../_images/e7b1e36dde1ec7680c1072caf99dd2c1067a845e3b026e93e7f9554dde3650e7.png