Polynomial regression: Difference between revisions

From Rosetta Code
Content added Content deleted
(Using Template:Libheader, instead of Template:Library)
m (→‎{{header|Python}}: How did we not catch this before?)
Line 13: Line 13:
This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
=={{header|Python}}==
=={{header|Python}}==
'''Interpreter:''' [[Python]]
[[Category:Python]]


{{libheader|numpy}}
{{libheader|numpy}}

Revision as of 21:37, 19 February 2008

Task
Polynomial regression
You are encouraged to solve this task according to the task description, using any language you may know.

Find an approximating polynom of known degree for a given data.

Example

For input data:

x = {0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10};
y = {1,   6,  17,  34,  57,  86, 121, 162, 209, 262, 321};

The approximatting polynom is:

   2
3 x + 2 x + 1

Here, polynom's coefficients are (3, 2, 1).

This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.

Python

Library: numpy
>>> x = [0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10]
>>> y = [1,   6,  17,  34,  57,  86, 121, 162, 209, 262, 321]
>>> coeffs = numpy.polyfit(x,y,deg=2)
>>> coeffs
array([ 3.,  2.,  1.])

Substitute back received coefficients.

>>> yf = numpy.polyval(numpy.poly1d(coeffs), x)
>>> yf
array([   1.,    6.,   17.,   34.,   57.,   86.,  121.,  162.,  209., 262.,  321.])

Find max absolute error.

>>> '%.1g' % max(y-yf)
'1e-013'

Example

For input arrays `x' and `y':

>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]
>>> p = numpy.poly1d(numpy.polyfit(x, y, deg=2), variable='N')
>>> print p
       2
1.085 N + 10.36 N - 0.6164

Thus we confirm once more that for already sorted sequences the considered quick sort implementation has quadratic dependence on sequence length (see Example section for Python language on Query Performance page).