
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "auto_examples/polyfit.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_auto_examples_polyfit.py>`
        to download the full example code

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_auto_examples_polyfit.py:


Polynomial Fitting
==================

A quick demonstration of polynomial fitting.

.. GENERATED FROM PYTHON SOURCE LINES 7-37



.. image-sg:: /auto_examples/images/sphx_glr_polyfit_001.png
   :alt: polyfit
   :srcset: /auto_examples/images/sphx_glr_polyfit_001.png, /auto_examples/images/sphx_glr_polyfit_001_2_00x.png 2.00x
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    I found the minimum here at 2.330166836973558






|

.. code-block:: Python

    from pylab import *
    from pyspecdata import *
    # {{{ generate fake data
    x = nddata(r_[0:10:7j], 'x')
    y = (x-2.0)**2
    y.add_noise(2)
    # }}}
    plot(y,'o')
    c = y.polyfit('x', order=2)
    assert len(c)==3
    # math for min:
    # a(x-b)²= ax² - 2abx + ab²
    # c₂ = a
    # c₁ = -2ab
    # c₀ = ab²
    # b = -c₁/(c₂2)
    print("I found the minimum here at",-c[1]/c[2]/2)
    # generate a polynomial that's more finely spaced by setting the
    # `npts` parameter.  This is a shortcut for:
    # x = nddata(r_[0:10:300j], 'x')
    # followed by
    # plot(x.eval_poly(c,'x'))
    plot(y.eval_poly(c,'x', npts=300))
    # {{{ not a good idea, but force the y intercept to 0
    #     to show the code works
    c = y.polyfit('x', order=3, force_y_intercept=0)
    x = nddata(r_[0:10:100j], 'x')
    plot(y.eval_poly(c,'x', npts=300))
    # }}}
    show()


.. rst-class:: sphx-glr-timing

   **Total running time of the script:** (0 minutes 0.308 seconds)


.. _sphx_glr_download_auto_examples_polyfit.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: polyfit.ipynb <polyfit.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: polyfit.py <polyfit.py>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
