Reputation: 137
I'm really new to programming, and I can't figure out how to use a Numpy array to be manipulated in a function such as P**2
.
import math
import numpy
span_x = numpy.array([0,250,500,750,1000])
P = span_x
example = P**2
span_y = [example for i in P]
y = float(input("Enter y: "))
bracket1 = min(span_y, lambda span_y: abs(span_y-y))
if bracket1 < y:
for i in span_y:
bracket2 = span_y[span_y.index(bracket1) + 1]
else:
for i in span_y:
bracket2 = span_y[span_y.index(bracket1) - 1]
print "Brackets: ", bracket1, bracket2
I've tried not using a Numpy array, but received a TypeError.
My main issue is that I have this array of x-values (span_x
) that I want to put into a function like P**2
and get y-values (span_y
) in an array. Then, the user inputs a y-value and I want to check which y-value in span_y
is closest to this input, and that is bracket1
. bracket2
is the second closest y-value. I would love some help!
Upvotes: 2
Views: 1554
Reputation: 58885
In NumPy you can and should vectorize the operations like:
span_y = span_x**2
y = float(input("Enter y: "))
bracket1 = np.array((span_y, np.abs(span_y - y))).min(axis=0)
bracket2 = np.zeros_like(bracket1)
bracket2[ bracket1 < y ] = np.roll(span_y, 1)
bracket2[ bracket1 >= y] = np.roll(span_y, -1)
Upvotes: 1
Reputation: 25329
span_y
is a list of 1D-arrays so min
doesn't work as you expect and returns a function. After that span_y.index(bracket1)
raises an exception. span_y
should be initialized like this
span_y = list(example)
Pass your key function (lambda) in min
as a named parameter as said in documention.
bracket1 = min(span_y, key = lambda span_y: abs(span_y-y))
Upvotes: 1