Finding the minimum value of a quadratic within a range

592 Views Asked by At

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...
1

There are 1 best solutions below

7
On BEST ANSWER

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)