the problem is not complex number itself, but calculations that you perform. First you do different things in Matlab alg (the version that you showed at least) and in C++. Here is how you should port this code to C++.
#include <cstdlib>
#include <iostream>
#include <complex>
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
double pi = 3.1415926535897;
double N = 512;
double M = 512;
double lambda = 632e-9;
double X = 12.1e-6;
double k = (2 * pi) / lambda;
double z0 = (N * pow(X, 2)) / lambda;
std::complex<double> hx, hy; // Both definitions don't work
//double hy;
int j = 1;
//for (int j=0; j < N; j++){
hy = (exp(j*k*z0) / (j*lambda))*exp(j*pi/(z0*lambda)*pow(X,2)*pow(j,2));
cout << hy <<endl;
//}
system("pause");
return 0;
}
now the problem is in your lambda = 632e-9
which is close to zero, then k is very big k = (2 * pi) / lambda;
as the inverse of something which approaches 0, and in turn
exp(j*k*z0)
is very big, and this
(exp(j*k*z0) / (j*lambda))
even more. Then this
(exp(j*k*z0) / (j*lambda))*exp(j*pi/(z0*lambda)
is huge, and the remaining factor pow(X,2)*pow(j,2))
is meaningful. So then
cout << hy <<endl;
will print (inf,0)
even for lambda = 0.0001; (how about 632e-9 !).
However you can still print it if you use small enough j
value to absorb huge k
value in exp (j
is also in denominator but de l'Hopital rule will assure this will be smaller).
As follows from your comments (not your code) you wanted j
to be complex number z=1i. Then the solution is to change
double j =1;
to
std::complex<double> j(0,1);
SOLUTION:
int main(int argc, char** argv) {
double pi = 3.1415926535897;
double N = 512;
double M = 512;
double lambda = 0.00001;//632e-9;
double X = 12.1e-6;
double k = (2 * pi) / lambda;
double z0 = (N * pow(X, 2)) / lambda;
std::complex<double> hx, hy;
std::complex<double> j(0,1);
hy = (exp(j*k*z0) / (j*lambda))*exp(j*pi/(z0*lambda)*pow(X,2)*pow(j,2));
cout << hy <<endl;
return 0;
}