how do we pass a complex no. to a C++ program
the real and imaginary values are dependent on some variables which are calculated at runtime
the real and imaginary values are dependent on some variables which are calculated at runtime
#include <iostream> #include <complex> using namespace std; int main() { complex<double> c1(0.0,1.0), c2; // complex numbers with double components c2=pow(c1,2.0); cout << "The square of " << c1 << " is " << c2 << endl; system("pause"); }
#include <iostream> #include <complex> #include <iomanip> #include <math.h> using namespace std; // check root value complex<double> check(double a, double b, double c, double d, complex<double> x) { return a*x*x*x + b*x*x + c * x + d; } // determine roots of cubic equation // a*x^3 + b*x^2 + c*x + d =0 // algorithm from http://www.1728.com/cubic2.htm void cubic(double a, double b, double c, double d) { double x1, x2, x3, x1r, x1i=0, x2i, x3i=0; cout << a << " " << b << " " << c << " d " << d << endl; double f =((3*c/a) - (b*b/(a*a)))/3; cout << "f " << f << endl; double g=(2*b*b*b/(a*a*a)-9*(b*c/(a*a))+27*d/a)/27; cout << "g " << g << endl; double h=(g*g)/4+f*f*f/27; cout << "h " << h << endl; if(h <= 0) { if(f == 0 && g == 0 && h == 0) // all three roots real and equal x1 = x2 = x3 =-pow(d/a, 1/3.0); else // three real roots { double i=sqrt((g*g/4)-h); cout << "i " << i << endl; double j=pow(i, 1/3.0); cout << "j " << j << endl; double k=acos(-(g/(2*i))); cout << "k " << k << endl; double l=-j; cout << "l " << l << endl; double m=cos(k/3); cout << "m " << m << endl; double n=sqrt(3.0)*sin(k/3); cout << "n " << n << endl; double p=-(b/(3*a)); cout << "p " << p << endl; x1=2*j*cos(k/3)-(b/(3*a)); x2=l*(m+n)+p; x3=l*(m-n)+p; } cout << "x1 " << x1 << endl; cout << "x2 " << x2 << endl; cout << "x3 " <<x3 << endl; } else // one real, two complex roots { double r=-(g/2)+sqrt(h); cout << "r " << r << endl; double s=pow(r, 1/3.0); cout << "s " << s << endl; double t=-(g/2)-sqrt(h); cout << "t " << t << endl; double u; if(t<0) u=-pow(-t, 1/3.0); else u=-pow(t, 1/3.0); cout << "u " << u << endl; x1=(s+u)-(b/(3*a)); cout << "x1 " << x1 << endl; x2=-(s+u)/2 -(b/(3*a)); x2i= (s-u)*sqrt(3.0)/2; cout << "x2 " << x2 << " +i " << x2i << endl; x3=x2;; x3i=-x2i; cout << "x3 " << x3 << " +i " << x3i << endl; } cout << "check x1 " << check(a, b, c, d, complex<double>(x1, 0)) << endl; cout << "check x2 " << check(a, b, c, d, complex<double>(x2, x3i)) << endl; cout << "check x3 " << check(a, b, c, d, complex<double>(x3, x3i)) << endl; } int main() { cout << "enter a, b, c, and d "; double a, b, c, d; cin >> a >> b >> c >> d; cubic(a, b, c, d); system("pause"); }
Comment