0

Given a quadratic function, that is f(x) = ax^2 + bx + c, what is the fastest way to find x in [-1, 1] which minimizes f(x)?

So far this is the function I've come up with:

double QuadraticMinimizer(double a, double b, double c) {   
    double x = 1 - 2*(b > 0);
    if (a > 0) {
        x = -b/(2*a);
        if (fabs(x) > 1)
            x = Sign(x);
    }
    return x;
}

Is it possible to do better?

Regexident
  • 29,441
  • 10
  • 93
  • 100
user92382
  • 369
  • 3
  • 12

1 Answers1

1

There is no "fastest way" because the running time depends on the particular machine and the particular distribution of the input parameters. Also, there is not much that you can remove from the initial code.

If the location of the extremum -b/2a frequently falls outside of the interval [-1,1], you can avoid the division in those cases.

If you allow to hack the sign bit from the floating-point representation to implement fast abs, sgn and setsgn functions, you can use something like

a*= -2;
if (hack_abs(b) >= hack_abs(a))
  return hack_setsgn(1, hack_sgn(a) ^ hack_sgn(b));

return b / a;

You can also try with the more portable copysign function.