user2741697
user2741697

Reputation: 17

Return value for which a function reaches its smallest negative value in python

It's pretty late, so I don't know how clear this will be.

I have a function f(x), I want to get the value of x from a list for which f(x) reachest the smallest negative value, namely:

x = [0, 2, 4, 6]
f(x) = [200, 0, -3, -1000]

In this case, I would like something to return the value 4 in x, which gave me -3. I don't want the absolute minimum (-1000), but the negative value with the lowest absolute value.

I hope that makes sense, thanks a lot for your help.

UPDATE

I was trying to simplify the problem, maybe too much. Here's the thing: I have a list of 2D points that form a polygon and I want to order them clockwise.

For that, I take the cross product between each point and the rest and select the next point based on getting the negative cross product (which tells me the sense of rotation) from the previous and which has the smallest absolute value (which tells me it really is the next point).

so, say:

x = [(1,1), (-1,-1), (-1,1), (1,-1)]

and I would like to get

x = [(1,1), (1,-1), (-1,-1), (-1,1)]

I'm doing

for point in x:
   cp = [numpy.cross(point, p) for p in x]
   # and then some magic to select the right point...

Thanks for your help again.

Upvotes: 0

Views: 106

Answers (4)

Mario Rossi
Mario Rossi

Reputation: 7799

The following solution should work well in most cases

    [ z for z in x if f(z) == max( f(y) for y in x if f(y) < 0 ) ]

One characteristic of this solution is that if there is a repetition, i.e. several x's producing the same biggest negative, all of them will be returned.

Upvotes: 0

Joohwan
Joohwan

Reputation: 2512

x = [0, 2, 4, 6]
fx = [200, 0, -3, -1000]

print(x[fx.index(max(n for n in fx if n < 0))])

Upvotes: 0

Xevelion
Xevelion

Reputation: 869

a = [0, 2, 4, 6]
b = [200, 0, -3, -1000]

value = max([x for x in b if x < 0])
print a[b.index(value)]

Upvotes: 2

Tom
Tom

Reputation: 4592

Try this:

inputs = [0, 2, 4, 6]
outputs = [200, 0, -3, -1000]
max = min(outputs)
for n in outputs:
    if n >= 0:
        continue
    if n > max:
        max = n
print inputs[outputs.index(max)]

Upvotes: 1

Related Questions