roots of piecewise cubic hermite interpolator with python

早过忘川 提交于 2019-12-10 15:48:25

问题


I would like to do some piecewise cubic hermite interpolation and get the roots of the polynomials. (I used to do this in matlab but would now like to implement this in python 3.4).
I tried to use the scipy PchipInterpolator. Interpolation is OK but when I tried to retrieve the roots I got this error...
I now am stuck here and could'nt find any workaround. Here is a simple code reproducing what I do and the exact error message...

import matplotlib.pyplot as plt
from scipy import interpolate, __version__
import numpy as np

print('numpy : ' + np.__version__)
print('scipy :' + __version__)

x = np.arange(10)
y = [1., 1., 3., 2., 1., 1., 1.5, 2., 8., 1.]
f = interpolate.PchipInterpolator(x, y, axis=0, extrapolate=None)
print(f.roots()) # this produces an error !

xnew = np.arange(0, 9, 0.1)
ynew = f(xnew)   # use interpolation function returned by `PchipInterpolator`
plt.plot(x, y, 'o', xnew, ynew, '-')
plt.show()

The error message :

numpy : 1.10.1
scipy :0.17.1
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    print(f.roots()) # this produces an error !
  File "/usr/local/lib/python3.4/dist-packages/scipy/interpolate/_monotone.py", line 105, in roots
    return (PPoly.from_bernstein_basis(self._bpoly)).roots()
AttributeError: 'PchipInterpolator' object has no attribute '_bpoly'

Process finished with exit code 1

However scipy docs say : "roots() Return the roots of the interpolated function."

What am I missing here?


回答1:


This is a bug in scipy.

(Please report it on https://github.com/scipy/scipy/issues)

As a workaround, you can convert to the power basis manually:

In [1]: from scipy.interpolate import pchip

In [2]: import numpy as np

In [3]: x = np.arange(10)

In [4]: y = [1., 1., 3., 2., 1., 1., 1.5, 2., 8., 1.]

In [5]: s = pchip(x, y)

In [6]: from scipy.interpolate import PPoly

In [7]: pp = PPoly.from
PPoly.from_bernstein_basis  PPoly.from_spline

In [7]: pp = PPoly.from_bernstein_basis(s)

In [8]: pp.roots()
Out[8]: array([  9.07179677,  22.92820323])

EDIT: and if do use this workaround and you have non-default axis, best check that the axis is handled when converting. If it's not, please report it too.



来源:https://stackoverflow.com/questions/38234448/roots-of-piecewise-cubic-hermite-interpolator-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!