Find slope of function given empirical data.

Peter Otten __peter__ at web.de
Wed Jun 30 03:28:52 EDT 2010


Thomas wrote:

> Trying to find slope of function using numpy.
> Getting close, but results are a bit off. Hope someone out here can
> help.

You don't make it easy to understand your post. In the future please try to 
rely more on plain english than on lots of numbers and code that doesn't 
run.

> import numpy as np
> 
> def deriv(y):
>     x = list(range(len(y)))
>     x.reverse()     # Change from [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>     x = np.array(x) #        to   [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>     y = np.array(y) # x.reverse() is used to put point 0 at end of
> list.
>     z = np.polyfit(x, y, 2)
>     print np.poly1d(z)
>     #  Returns:
>     #         2
>     #  3.142 x - 18.85 x + 35.13
>     #                              2
>     # Should be closer to   3.142 x  - 6.283 +
> 10   ????????????????????

To add one more question mark: how did you find that alternative?

Anyway, we can put both polynomials to a test:

>>> import numpy as np
>>> y = np.array([160.796416, 119.95572, 85.398208, 57.12388, 
35.132736,19.424776, 10.0, 6.858408, 10.0, 19.424776, 35.132736])
>>> x = np.arange(len(y), dtype=float)[::-1]
>>> p1 = np.poly1d(np.polyfit(x, y, 2))
>>> print p1
       2
3.142 x - 18.85 x + 35.13
>>> p2 = np.poly1d([3.142, -6.283, 10.0])
>>> print p2
       2
3.142 x - 6.283 x + 10

Now calculate the sum of the squares:

>>> np.sum((p1(x)-y)**2)
5.0683524299544787e-26
>>> np.sum((p2(x)-y)**2)
33028.342907811333

Conclusion: numpy's result is much better than what you suggest. 

Peter



More information about the Python-list mailing list