[Numpy-discussion] Improving numpy.interp

LB berthe.loic at gmail.com
Thu Nov 8 15:15:03 EST 2007


I often need to make a linear interpolation for a single scalar value
but this
is not very simple with numpy.interp :
>>> import numpy as n
>>> n.__version__
'1.0.5.dev4420'
>>> xp = n.arange(10)
>>> yp = 2.5 + xp**2 -x
>>> x = 3.2
>>> n.interp(x, xp, yp)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: object of too small depth for desired array

So I use the following trick (which is really ugly) :
>>> n.interp([x], xp, yp)[0]
7.7000000000000011

Did I miss an obvious way to do it ?

If not, I'd be tempted to patch interp to let it accept scalar values
as first
argument as follow :
>>> def interp(x, *args, **kwds):
...     if type(x) in (float, int):
...         return n.interp([x], *args, **kwds).item()
...     else :
...         return n.interp(x, *args, **kwds)
...
>>>
>>> interp(x, xp, yp)
7.7000000000000011
>>> interp([x,2*x], xp, yp)
array([  7.7,  38.5])

--
LB




More information about the NumPy-Discussion mailing list