How to fit parametric equations to data points in Python
Question: I am looking for a way to fit [parametric
equations](https://en.wikipedia.org/wiki/Parametric_equation) to a set of data
points, using Python.

As a simple example, given is the following set of data points:

    
    
    import numpy as np
    x_data = np.array([1, 2, 3, 4, 5])
    y_data = np.array([2, 0, 3, 7, 13])
    

Using `t` as the parameter, I want to fit the following parametric equation to
the data points,

    
    
    t = np.arange(0, 5, 0.1)
    x = a1*t + b1
    y = a2*t**2 + b2*t + c2
    

that is, have Python find the values for the coefficients `a1`, `b1`, `a2`,
`b2`, `c2` that fits `(x,y)` best to the data points `(x_data, y_data)`.

Note that the `y(t)` and `x(t)` functions above only serve as examples of
parametric equations. The actual functions I want to fit my data to are much
more complex, and in those functions, it is not trivial to express `y` as a
function of `x`.

Help will be appreciated - thank you!


Answer: Since the relation between `x` and `y` is a quadratic one, you can use
`np.polyfit` to get the coefficients. According to your equations, your `x`
and `y` relation is:

`y = a2*((x-b1)/a1)**2 + b2*((x-b1)/a1) + c2`

Using polyfit, we get

    
    
    y_data = np.array([2, 0, 3, 7, 13])
    x_data = np.array([1, 2, 3, 4, 5])
    np.polyfit(x_data,y_data,2)
    [p2,p1,p0] = list(array([ 1.21428571, -4.38571429,  4.8       ]))
    

The values of `a1, b1, a2, b2, c2` can be obtained by solving the following
eqns

`p2 = a2/a1**2`

`p1 = -2b1*a2/a1**2 + b2/a1`

`p0 = a2*b1**2/a1**2 -b2*b1/a1 + c2`

