1
$\begingroup$

Given any quadratic equation of the form $y=ax^2+bx+c$, I want to find the minimum value for a specific range of $x$.

My programmer brain can do it in a branchy, algorithmic way as follows, but is there a more elegant solution?

  • if the $a$ coefficient is positive,
    • and the end of my range is before the lowest point of the quadratic,
      • return the end of my range
    • and the start of my range is after the lowest point of the quadratic,
      • return the start of my range
    • and the lowest point of the quadratic occurs in the middle of my range,
      • return the lowest point of the quadratic
  • if the $a$ coefficient is negative, etc...
  • 0
    Your first half wouldn't look so branchy if you wrote it simply as $\min(\max(x_1, x_0), x_2)$, with $x_0, x_1, x_2$ as in Isaac's answer.2011-01-27

1 Answers 1

3

Given that your range is $x_0$ to $x_2$, let $x_1=-\frac{b}{2a}$. The minimum value of $y$ occurs at $x_0$, $x_2$, or $x_1$ (if $x_0\le x_1\le x_2$). So, compute $y_0=ax_0^2+bx_0+c$, $y_1=ax_1^2+bx_1+c$ (if $x_1$ is in the range), and $y_2=ax_2^2+bx_2+c$ and pick whichever is the least of those.

edit to be clear, what I'm suggesting is something like:

def quadMin(a, b, c, xmin, xmax):   q0 = (a * xmin + b) * xmin + c   q2 = (a * xmax + b) * xmax + c   x1 = -b / (2*a)   if (xmin < x1) and (x1 < xmax):     q1 = (a * x1 + b) * x1 + c     return min(q0, q1, q2)   else:     return min(q0, q2) 
  • 0
    OK JEEZE YOU GUYS you can have the tick. :)2011-01-28