Kim Nguyen
Kim Nguyen

Reputation: 21

Create a recursive function that solves this equation

Create a recursive function that solves this equation iteratively: 2x3 – 10x +4 = 0. And here is the solution, i don't understand why do I get the result 2 when I pass value of 1 and 0.40400000 when I pass value of 0 to method solve(). How does it work?

public static double solve(double x)
{
    double y = 2*x*x*x - 10*x + 4;
    if (y > -0.01 && y < 0.01)
        return x;
    else return solve(x + 0.001);
}

public static void main(String[] args) {
    System.out.println(solve(1));
    // 0.40400000   when starting from 0
    // 2             when starting from 1
}

Upvotes: 0

Views: 319

Answers (1)

tobias_k
tobias_k

Reputation: 82929

Basically, what the function does is: it just tests all possible values for x in steps of 0.001 until it finds one that satisfies the equation with an error of less than 0.01.

The function is more or less equivalent to the following, which might be easier to understand:

public static double solve(double x) {
    while (true) {                      // repeat...
        double y = 2*x*x*x - 10*x + 4;  // calculate y
        if (-0.01 < y && y < 0.01)      // y close to 0 ?
            return x;                   // "good enough" solution found
        x += 0.001;                     // try next value for x
    }
}

Your equation has multiple solutions (see Wolfram Alpha for a visualisation), so depending on the starting point, there can be different solutions. You should get another solution of you start with e.g. x = -3.

There are, however, several problems with that function. First, it will just run infinitely if you pass an x that is larger than the largest x that solves the equation, so it might be reasonable to also provide an upper limit for x. But it might also miss a solution if the slope is very steep, so it goes from < -0.01 to > +0.01 in one step. A better approach might be just to memorize the sign of y and see in which step it changes from positive to negative or vice versa, or a combination of the two in case of a minimum or maximum at 0.

Upvotes: 2

Related Questions