Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract value of a numeric array function in numpy

Tags:

python

numpy

If I define a function whit two array, for instance like this:

from numpy import *
x = arange(-10,10,0.1)
y = x**3

How can I extract the value of y(5.05) interpolating the value of the two closer point y(5) and y(5.1)? Now if I want find that value, I use this method:

y0 = y[x>5][0]

And I should obtain the value of y for x=5.1, but I think that exist better methods, and probably they are the correct ones.

like image 305
nunzio13n Avatar asked Dec 31 '25 13:12

nunzio13n


1 Answers

There's numpy.interp, if linear interpolation will suffice:

>>> import numpy as np
>>> x = np.arange(-10, 10, 0.1)
>>> y = x**3
>>> np.interp(5.05, x, y)
128.82549999999998
>>> 5.05**3
128.787625

And there are a bunch of tools in scipy for interpolation [docs]:

>>> import scipy.interpolate
>>> f = scipy.interpolate.UnivariateSpline(x, y)
>>> f
<scipy.interpolate.fitpack2.LSQUnivariateSpline object at 0xa85708c>
>>> f(5.05)
array(128.78762500000025)
like image 143
DSM Avatar answered Jan 02 '26 03:01

DSM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!