.. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_intro_scipy_auto_examples_plot_curve_fit.py: =============== Curve fitting =============== Demos a simple curve fitting First generate some data .. code-block:: python import numpy as np # Seed the random number generator for reproducibility np.random.seed(0) x_data = np.linspace(-5, 5, num=50) y_data = 2.9 * np.sin(1.5 * x_data) + np.random.normal(size=50) # And plot it import matplotlib.pyplot as plt plt.figure(figsize=(6, 4)) plt.scatter(x_data, y_data) .. image:: /intro/scipy/auto_examples/images/sphx_glr_plot_curve_fit_001.png :class: sphx-glr-single-img Now fit a simple sine function to the data .. code-block:: python from scipy import optimize def test_func(x, a, b): return a * np.sin(b * x) params, params_covariance = optimize.curve_fit(test_func, x_data, y_data, p0=[2, 2]) print(params) .. rst-class:: sphx-glr-script-out Out: .. code-block:: none [3.05931973 1.45754553] And plot the resulting curve on the data .. code-block:: python plt.figure(figsize=(6, 4)) plt.scatter(x_data, y_data, label='Data') plt.plot(x_data, test_func(x_data, params[0], params[1]), label='Fitted function') plt.legend(loc='best') plt.show() .. image:: /intro/scipy/auto_examples/images/sphx_glr_plot_curve_fit_002.png :class: sphx-glr-single-img **Total running time of the script:** ( 0 minutes 0.026 seconds) .. _sphx_glr_download_intro_scipy_auto_examples_plot_curve_fit.py: .. only :: html .. container:: sphx-glr-footer :class: sphx-glr-footer-example .. container:: sphx-glr-download :download:`Download Python source code: plot_curve_fit.py ` .. container:: sphx-glr-download :download:`Download Jupyter notebook: plot_curve_fit.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_