Home > Software design >  Simple Iterations
Simple Iterations

Time:07-13

could you help me with the method of simple iterations, I wrote an algorithm but for some reason it tends to infinity, Newton's algorithm solves this task without problems, but there is a problem with this algorithm ... Can you tell me what needs to be done to do it its fully functional?

x^3 3*x^2-2=0

 static void Main(string[] args)
    {
        Console.WriteLine(Solve(-3.0));    
    }

    static double function(double x) => Math.Pow(x, 3)   3 * Math.Pow(x, 2) - 2;

    static double Solve(double x)
    {
        double eps = 0.000001;
        double y;
        double b;
        do
        {
            y = function(x);

            b = Math.Abs(y - x);

            x = y;

        }while (b >= eps);

        return y;
    }

CodePudding user response:

You have two problems.

The first is that fixed point methods solve problems of the form f(x) = x and not f(x) = 0.

You could solve that by trying to solve x = x^3 3*x^2-x-2, but then you run into the second problem. And that is that unless you guess very close to the answer, x^3 is going to grow on every iteration and you'll go off to infinity.

Therefore you need to find a problem of the form f(x) = x to solve where f tends to converge, not diverge.

I would suggest you rewrite it to x^3 = -3*x^2 2 and then take cube roots so you're now solving x = (-3 x^2 2)^(1/3). C# may not like fractional powers of negative numbers, so you'll need to check the sign and manually deal with that knowing that (-y)^(1/3) = -y^(1/3).


Here is sample code in Python showing the idea.

def iteration (x):
    y = -3 * x*x   2
    if y < 0:
        return - (-y)**(1/3)
    elif 0 < y:
        return y**(1/3)
    else:
        return 0


x = 100
for i in range(100):
    print(i, x)
    x = iteration(x)
  • Related