Search code examples
javacalculus

Determine extrema of function


I'm running into an issue in which the minima is not being correctly set. The maxima is setting perfectly, but I know that the minima should be less than 0. Running this snippet, it seems like the minima is never being set. Any ideas?

edit: The curve points should be from -1 to 3. Here's an image: The curve

public class FindingExtrema {
    public static void main(String[] args) {
        double lowestPoint = 0;
        double highestPoint = 0;
        double y;

        double x = -1;
        int timesCalculated = 0;

        while (x <= 3) {
            y = run(x);

            if (y < lowestPoint) {
                lowestPoint = y;
                System.out.printf("y: %1$.5f", y);
            }

            if (y > highestPoint) {
                highestPoint = y;
            }

            x += .00001;
            timesCalculated++;
        }

        System.out.println("Done!");
        System.out.printf("Lowest: %1$.5f, Highest: %2$.5f; Calculated %3$d times\n", lowestPoint, highestPoint, timesCalculated);
    }

    private static double run(double x) {
        return Math.cbrt(2 * x) - Math.sqrt(8 * x) + x + 16;
    }
}

Solution

  • The expression

    Math.cbrt(2 * x) - Math.sqrt(8 * x) + x + 16;
    

    is not equivalent to the right hand side for the equation of your graph - you are getting cube root confused with cubing and square root confused with squaring.

    The correct expression is

    (2 * x * x * x) - (8 * x * x) + x + 16