2

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!

6
  • 3
    Please, always post full tracebacks. Commented May 16, 2015 at 2:21
  • Please, do a search on the error - see the 'Related' column to see how many other SO questions have the same subject line. Commented May 16, 2015 at 2:54
  • Does the ValueError occur on line: if bracket1 < y:? Commented May 16, 2015 at 2:56
  • Thank you for the feedback. The error occurs at: bracket2 = span_y[span_y.index(bracket1) - 1] Commented May 16, 2015 at 15:50
  • As Alik noted bracket1 is not an array like one those in span_y. You need to test how you generate it. Commented May 16, 2015 at 15:59

2 Answers 2

1

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))
Sign up to request clarification or add additional context in comments.

Comments

1

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)

2 Comments

I tried this, and it got rid of my Error Message, but when I print bracket1, bracket2 both outputs display long arrays when the answers should really just each be one value. Why is that please?
@theo1010 it was a bit unclear from your question to understand what you really wanted, so I built this example using vectors... I hope this example clarifies your doubts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.