Conor Taylor
Conor Taylor

Reputation: 3108

Get minimum point(s) of numpy.poly1d curve

I have a numpy.poly1d polynomial as follows:

c = np.poly1d([2,-4,-28,62,122,-256,-196,140,392,240,72])

The curve looks like this when graphed in the range -2.5 <= x <= 2.5:

enter image description here

How can I find the minimum point(s) of this curve within the given range, without using the discrete values used to graph the curve (by this I mean using only the continuous poly1d object)?

Upvotes: 7

Views: 9378

Answers (2)

joojaa
joojaa

Reputation: 4434

OK a bit different functions than @matiasg aim is to make more copyable code and use as much vectorized code as possible.

import numpy as np
from matplotlib.pyplot import *

c = np.poly1d([2,-4,-28,62,122,-256,-196,140,392,240,72])

crit = c.deriv().r
r_crit = crit[crit.imag==0].real
test = c.deriv(2)(r_crit) 


# compute local minima 
# excluding range boundaries
x_min = r_crit[test>0]
y_min = c(x_min)
plot( x_min, y_min, 'o' )

xc = np.arange(-2.5, 2.6, 0.02)
yc = c(xc)
plot( xc, yc)

xlim([-2.5,2.5])
show()

result

Image 1: Result. Note there is another local minima just outside your bounds ;)

Upvotes: 11

matiasg
matiasg

Reputation: 2019

This gives you the critical points, i.e. those x in the interval such that the derivative is zero or they lie in the boundary of the interval. From that, it should only be evaluating and taking min.

In [22]: p = numpy.poly1d([2,-4,-28,62,122,-256,-196,140,392,240,72])

In [23]: bounds = [-2.5, 2.5]

In [24]: crit_points = bounds + [x for x in p.deriv().r if x.imag == 0 and bounds[0] < x.real < bounds[1]]

In [25]: crit_points
Out[25]: 
[-2.5,
 2.5,
 (-2.0243100544390678+0j),
 (1.8753707038871632+0j),
 (1.2307367723613383+0j),
 (-0.41217268372324861+0j)]

From the graph, in this case it seems that the min is the last one.

Upvotes: 4

Related Questions