-
Complex Numbers
Hi
I'm having a problem with complex numbers. I have an equation that I must use. However, most of the time the result is complex, and I think I just need the real part. This doesn't work:
Code:
#define sigma 0.3
#include <complex>
.....
complex<double> num;
double y = 0;
float x = ...just something
num = sqrt(-2.0f*sigma*sigma*log(1.0f - x)); //apparently a pc doesn't know
//how to do this
y = real(num);
I haven't found anything about how to do this. I printed out the variable y and it usually just shows "1.#QO", but I need the real part of the result of the equation.
Please tell me there is a way do to this... :)
-
Is this what you want?
Code:
#include <iostream>
#include <complex>
using namespace std;
const double sigma(0.3);
int main()
{
double x = .3;
complex<double> num = sqrt(-2.0 * sigma * sigma * log(1.0 - x));
double y = num.real();
cout << y << endl;
return 0;
}
-
Yeah, except that still doesn't work. In the equation x can be between 0 and 100 (part of my assignment), so the result is usually complex, and I don't know how to handle it.
The complete program:
Code:
#include <iostream>
#include <ctime>
#include <fstream>
#include <complex>
#include <cmath>
using namespace std;
#define sigma 0.3f
#define pi 3.14159f
#define tab '\t'
void randomGenerator(float *& array, float a, float b, int count)
{
array = new float[count];
srand(time(NULL));
for(int i = 0; i < count; i++)
{
array[i] = ((b-a)*((float)rand()/(float)RAND_MAX))+a;
}
//http://www.codeguru.com/forum/showthread.php?t=351834
}
int main()
{
ofstream f_out;
f_out.open("rayleigh.txt");
f_out.precision(4);
complex<double> num;
double y = 0;
float a, b;
int count;
bool option = 0;
float * array;
cout << "Enter the random number range(smallest number first): ";
cin >> a >> b;
cout << endl << "Enter the desired number of random numbers: ";
cin >> count;
cout << "Negate half of the numbers? (1 for yes): ";
cin >> option;
cout << endl << "Generating random numbers..." << endl;
randomGenerator(array, a, b, count);
for(int i = 0; i < count; i++)
{
num = sqrt(-2.0f*sigma*sigma*log(1.0f - array[i]));
y = num.real();
// if(option == 1)
// {
// if(((float)rand()/(float)RAND_MAX) > 0.5f)
// y = -y;
// }
f_out << array[i] << tab << y << endl;
}
cout << "Rayleigh distribution output to rayleigh.txt. " << endl;
cout << "Press any key to continue..." << endl;
cin.get();
cin.get();
delete[] array;
f_out.close();
return 0;
}
-
To use the complex version of sqrt(), you will need to make the value into a complex number FIRST, then call sqrt(), e.g.
Code:
complex<double> num = sqrt(complex<double>(-2.0 * sigma * sigma * log(1.0 - x), 0));
Otherwise, it will just call the regular sqrt(double) function, which of course doesn't understand how to deal with the negative value.
--
Mats