Operations with complex numbers in C - Calculation of roots of an equation by Newton Raphson's method

3

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

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

I have the following code, where I display the value of c and the program can rotate and get the real root of c = 0.99 .

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

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

I am 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();
}
    
asked by anonymous 14.04.2014 / 04:29

1 answer

1

If you are entering an infinite loop, the problem is in while(er>e); , which must always be true. So you should check that the assignment you make to er is correct: er=fabs((x2-x1)/x2); , and verify that the value set for the e constant is also correct. Since you are using fabs , you are only getting positive values, which, for the range of a float, however small (other than 0), will always be greater than e . I suggest that you use double instead of float for greater precision, and slightly decrease the accuracy of e for greater accuracy.

    
13.05.2014 / 04:59