how to find complex roots in c++ by newton-raphson method

ı would like to write using newton-raphson metod in c++.I wrote code basic equation in c++.but for complex root I have a problem.
[code]
#include<iostream>
#include<conio.h>
#include<cmath>
using namespace std;
double f(double x) {
return (pow(x,2)+1);
}
double f1(double x) {
return (2*x);
}
int main () {
double x=1+2i;
double tol=1e-6;
double err,errreal,errcomplex;
double xr;
double xc;
while (1) {
err=f(x)/f1(x);
xr=xr+errreal;
xc=xc-errcomplex;
x=x-err;
err=((xr+xc)+1)/2(xr+xc);
cout<<x<<" "<<f(x)<<" "<<endl;
if(fabs(err)<tol) break;
}
getch();
return 0;
}
could anybody help me please? to write code for complex root
f(x)=x^2+1
initial estimate x0=1+2i
If you have a working version in real variables then just change the type of x, err and the functions f and f1 to complex<double>, and use abs() instead of fabs().

Consult the reference for <complex> on this site if necessary, although you have to do little more than declare variables to be of complex type. You don't have to separate real and imaginary parts as in your code sample.

It would help on this forum if you put your code in code tags and avoided implementation-specific unnecessaries like conio.h.
Last edited on
#include<iostream>
#include<cmath>
#include<complex>
using namespace std;
double f(double x) {
return (pow(x,2)+1);
}
double f1(double x) {
return (2*x);
}
int main () {
complex <double> x=(1.0,2.0);
double tol=1e-6;
complex <double> err,errreal,errcomplex;
complex <double>xr;
complex <double> xci;
while (1) {

xr=xr+errreal;
xci=xci-errcomplex;
err=(xr+xci)+1/2(xr+xci);
x=x-err;

cout<<x<<" "<<f(x)<<" "<<endl;
if(abs(err)<tol) break;
}
return 0;
}
I wrote code again for complex number but something is wrong in my code.could anybody help me please?
You are working with complex variables, so both the arguments and the return values of your functions f and f1 should be complex<double>.

As I said in my previous post you do NOT need to split into real and imaginary parts. In particular, you do NOT need variables xr, xci, errreal or errcomplex at all.

You have actually gone backwards, because in your previous code you were correctly calculating
err=f(x)/f1(x);
Now you don't calculate an increment at all.

Please put code samples within code tags and give more information than "something is wrong in my code".
Last edited on
Topic archived. No new replies allowed.