-3

If I create a complex number with amplitude negativ (-1) and no phase (0), thus corresponding to a double of -1, and convert it back to amplitude and phase, the amplitude is not negative

complex<double> c;
c = polar(-1.0, 0.0);
cout << c << ", " << abs(c) << ", " << arg(c) << endl;

the output is

(-1, 0), 1, -3.14159

it should have been

(-1, 0), -1, 0

How can I get back the correct amplitude value?

Matthias Pospiech
  • 3,130
  • 18
  • 55
  • 76
  • 1
    polar(-1.0,0.0) => -180 degrees argument, 1 radius. Radius cannot be negative. – Jean-François Fabre Sep 06 '16 at 21:06
  • 2
    are you aware that the mapping (rho,theta)-(abs,arg) is not strictly bijective? –  Sep 06 '16 at 21:06
  • The right tool to solve such problems is your debugger. You should step through your code line-by-line *before* asking on Stack Overflow. For more help, please read [How to debug small programs (by Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). At a minimum, you should \[edit] your question to include a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example that reproduces your problem, along with the observations you made in the debugger. – πάντα ῥεῖ Sep 06 '16 at 21:09
  • @πάνταῥεῖ can you explain how a debugger would help in this case – M.M Sep 06 '16 at 22:54
  • @M.M Can you explain how to even debug that incomplete code? – πάντα ῥεῖ Sep 06 '16 at 22:57
  • No. So I don't think a debugger is the right tool to help with this problem. – M.M Sep 06 '16 at 22:59

2 Answers2

3

From a mathematical point of view, the magnitude (or modulus or absolute value) of a complex number should be a positive number (or 0).

Looking at the reference page for std::polar it's specified that:

Returns a complex number with magnitude r and phase angle theta. The behavior is undefined if r is negative or NaN, or if theta is infinite (since C++17)

You don't specify what compiler you are using, but it is kind enough to give you the "correct" result, a complex number with magnitude 1 and phase angle -π. Testing the same snippet with g++ 6.1 (-std=c++14) gave me:

(-1,-0), 1, -3.14159

The only difference is the negative zero, which is consistent with the negative angle.

Also note that a function like std::abs could return a negative number only if some error occured.

Bob__
  • 12,361
  • 3
  • 28
  • 42
1

You're confusing real and imaginary part with absolute and phase.

Try:

cout << c << ", " << real(c) << ", " << imag(c) << endl;

Also, absolute values can NEVER be negative by definition of polar coordinates. You could try with that:

complex<double> c;
c = polar(1.0, M_PI); //don't forget to include <cmath>
cout << c << ", " << abs(c) << ", " << arg(c) << endl;

And that will flip the phase and make the radius on the other direction of the polar coordinates.

The Quantum Physicist
  • 24,987
  • 19
  • 103
  • 189