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();
}
Care to do
#defines
with names likec
,e
andF(x)
because it can cause obscure errors. You better create aconst float
forc
ande
andF(x)
an even function.– Lucas Lima
Do not use
float
to work with fractions, its accuracy is very low. Use thedouble
orlong double
– Guilherme