Operations with complex numbers in C - Root calculation of an equation by the Newton Raphson method

Asked

Viewed 849 times

3

I have a problem with a language program C 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 c 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 present the value of c = 0.99 and the program can 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.

Would 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();
}
  • 2

    Care to do #defines with names like c, e and F(x) because it can cause obscure errors. You better create a const float for c and e and F(x) an even function.

  • 2

    Do not use float to work with fractions, its accuracy is very low. Use the double or long double

1 answer

1


If you’re entering an infinite loop, the problem is while(er>e);, which should always be true. This way, should check whether the assignment you make to er is correct: er=fabs((x2-x1)/x2);, in addition to checking whether the value defined for the constant e is also correct. How are you using fabs, is taking only positive values, which, for the range of a float, however small (other than 0), will always be greater than e. I suggest you use double in place of float for greater accuracy, and slightly decreasing the accuracy of e for greater accuracy.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.