Operations with complex numbers in C – Calculating the roots of an equation using the Newton Raphson method

Question:

I have a problem in a C language program that calculates the root of an equation using the Newton-Raphson method, specifically when the equation has complex roots.

In my case the equation I'm using will have real roots if the constant c in the equation is less than zero. For c greater than zero, the equation will have complex roots.

I have the following code, where I present the value of c = 0.99 and the program manages to run and get the real root of 5.796753 .

If the value of c is changed to any value greater than 1 the program enters an infinite loop and never converges.

Does anyone have any idea what should be done to converge on a complex root?

I'm passing the code in C:

#include<stdio.h>
#include<math.h>
#include<conio.h>
#include<complex.h>

#define c 0.99
#define e 0.00000000000000001
#define F(x) ((c/2)*((log(x+1)-log(x-1))+(2*x/(x*x-1))))

float frac(float a)
{
    float f1;
    f1=(1-((c*a/2)*(log(a+1)-log(a-1))));
    return f1;
}

int main()
{
    float x1,x2,f1=0,f2,er,d;
    printf("F(x) = 1-{(c*x/2)*[log(a+1)-log(x-1)]}\n\n");
    printf("Entre com o valor de x1: ");
    scanf("%f",&x1);
    printf("\nx1 = %f",x1);
    printf("\n________________________________________________________________________________\n");
    printf("     x1      |       x2      |      f1       |       f'1      |  |(x2-x1)/x2|  |  \n");
    printf("--------------------------------------------------------------------------------\n");
    do
    {
        f1=frac(x1);
        d=F(x1);
        x2=x1-(f1/d);
        er=fabs((x2-x1)/x2);
        printf("  %f   |    %f   |     %f  |     %f  |      %f  |   \n",x1,x2,f1,d,er);
        x1=x2;
    }
    while(er>e);
    printf("--------------------------------------------------------------------------------\n\n");
    printf("\n  A raiz da equacao: %f",x2);
    getch();
}

Answer:

If you're getting into an infinite loop, the problem is with while(er>e); , which must always be true. In this way, you should check if your assignment to er is correct: er=fabs((x2-x1)/x2); , in addition to verifying that the value defined for the constant e is also correct. As you are using fabs , you are only taking positive values, which, for the range of a float, however small (different from 0), will always be greater than e . I suggest that you use double instead of float for greater precision, and slightly lower the precision of e for greater accuracy.

Scroll to Top
AllEscort