[SciPy-User] Return type of scipy.interpolate.splev for input array of length 1
josef.pktd at gmail.com
josef.pktd at gmail.com
Mon Jan 18 10:59:46 EST 2010
On Sun, Jan 17, 2010 at 5:25 AM, Yves Frederix <yves.frederix at gmail.com> wrote:
> Hi,
>
> I stumbled upon the following unlogical behavior of
> scipy.interpolate.splev. When presented with a length-1 array, the
> output is converted to a scalar.
>
> <code>
> import scipy.interpolate
> import numpy as N
>
> x = N.arange(5.)
> y = N.arange(5.)
> tck = scipy.interpolate.splrep(x,y)
>
> x_eval = N.asarray([1.])
> y_eval = scipy.interpolate.splev(x_eval, tck)
>
> print 'scipy.interpolate.splev(x_eval, tck):', y_eval
> print 'type(x_eval):', type(x_eval)
> print 'type(y_eval):', type(y_eval)
> </code>
>
> with output
>
> <output>
> scipy.interpolate.splev(x_eval, tck): 1.0
> type(x_eval): <type 'numpy.ndarray'>
> type(y_eval): <type 'numpy.float64'>
> </output>
>
> It was rather unexpected that the type of input and output data are
> different. After checking interpolate/fitpack.py it seems that this
> behavior results from the fact that the length-1 case is explicitly
> treated differently (probably to be able to deal with the case of
> scalar input, for which scalar output is expected):
>
> 434 def splev(x,tck,der=0):
> <snip>
> 487 if ier: raise TypeError,"An error occurred"
> 488 if len(y)>1: return y
> 489 return y[0]
> 490
>
> Wouldn't it be less confusing to have the return value always have the
> same type as the input data?
I don't know of any "official" policy.
scipy.stats has switched for the most part to the same behavior. I
think, mainly it is just a convention to have a nicer output when the
return value is a scalar.
One problem with making the output depend on the input type or shape
is that in most functions I know, this information is not kept inside
the function. Usually the input of array_like (arrays, lists, tuples,
scalar numbers) is converted to an ndarray with np.asarray or
np.array.
The output then is independent of the input type (which hurts also if
a user wants to work with matrices or other subclasses of ndarrays).
On the other hand, if I want to use a list as input for convenience, I
don't really want a list as output, I want an ndarray.
That's my view, I don't really care in which direction the convention
goes, but I like the consistency.
Josef
> Cheers,
> YVES
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
More information about the SciPy-User
mailing list