Apr 26, 2020 at 4:30pm UTC
Hello,
I wrote a program for sorting complex numbers with C++.
To print the sign of the imaginary part of the number I wrote the below function. Is it true?
Thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
#include <iostream>
using namespace std;
struct Complex
{
double real;
double img;
};
void swap(Complex* xp, Complex* yp)
{
Complex temp = *xp;
*xp = *yp;
*yp = temp;
}
int main()
{
int n;
cout << "Number?:" ;
cin >> n;
Complex* myArray = new Complex[n];
for (size_t i = 0; i < n; i++)
{
cout << "Real: " ;
cin >> myArray[i].real;
cout << "Imaginary: " ;
cin >> myArray[i].img;
}
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (myArray[j].real > myArray[j + 1].real)
{
swap(&myArray[j], &myArray[j + 1]);
}
else if (myArray[j].real == myArray[j + 1].real)
{
if (myArray[j].img > myArray[j + 1].img)
{
swap(&myArray[j], &myArray[j + 1]);
}
}
}
}
cout << endl;
for (size_t i = 0; i < n; i++)
{
cout << myArray[i].real;
if (myArray[i].img < 0)
{
cout << myArray[i].img<<"i" ;
}
else
{
cout <<"+" << myArray[i].img << "i" ;
}
cout << endl;
}
}
Last edited on Apr 26, 2020 at 4:50pm UTC
Apr 26, 2020 at 4:50pm UTC
You can't meaningfully sort complex numbers.
Apr 26, 2020 at 4:55pm UTC
Thank you, could you please more explain?
Apr 26, 2020 at 6:07pm UTC
Shervan360 wrote:Thank you, could you please more explain?
At the moment, you are sorting by real part, or imaginary part if real parts are equal. But this will end up with massive discontinuities in the order relation.
Secondly, comparing two doubles for equality - within the finite accuracy of floating-point arithmetic - is asking for trouble.
Thirdly, think of the disastrous consequences. According to your scheme (with i the square root of -1):
-1 < i
OK, but then square it:
1 < -1
See the problem?
Last edited on Apr 27, 2020 at 7:44am UTC