Format of complex number in Python

后端 未结 4 1618
清歌不尽
清歌不尽 2020-12-18 19:13

I am wondering about the way Python (3.3.0) prints complex numbers. I am looking for an explanation, not a way to change the print.

Example:

>>         


        
4条回答
  •  离开以前
    2020-12-18 19:42

    The answer lies in the Python source code itself.

    I'll work with one of your examples. Let

    a = complex(0,1)
    b = complex(-1, 0)
    

    When you doa*b you're calling this function:

    real_part = a.real*b.real - a.imag*b.imag
    imag_part = a.real*b.imag + a.imag*b.real
    

    And if you do that in the python interpreter, you'll get

    >>> real_part
    -0.0
    >>> imag_part
    -1.0
    

    From IEEE754, you're getting a negative zero, and since that's not +0, you get the parens and the real part when printing it.

    if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
        /* Real part is +0: just output the imaginary part and do not
           include parens. */
    ...
    else {
        /* Format imaginary part with sign, real part without. Include
           parens in the result. */
    ...
    

    I guess (but I don't know for sure) that the rationale comes from the importance of that sign when calculating with elementary complex functions (there's a reference for this in the wikipedia article on signed zero).

提交回复
热议问题