I want to create a Java method which returns the lowest root of a quadratic equation in the interval (0, 1)
. If there are no solutions in the interval, return 1
. I need some help making this an efficient algorithm.
This is my current method:
public static float getLowestRoot(float A, float B, float C) {
float D = B*B - 4*A*C;
if(D < 0) return 1;
float sD = (float) Math.sqrt(D);
float x1 = (-B + sD) / (2*A);
float x2 = (-B - sD) / (2*A);
if(x2 < x1) {
float tmp = x2;
x2 = x1;
x1 = tmp;
}
if(x1 > 0 && x1 < 1) return x1;
if(x2 > 0 && x2 < 1) return x2;
return 1;
}
This method does the job but I was wondering if there is a way to compress the algorithm, because right now it feels bloated.