Skip to the content.

complex

contents

related file

memory layout

PyComplexObject stores two double-precision floating-point numbers inside.

The handling process and representation are mostly the same as the float object

layout

example

c = complex(0, 1)

example0

d = complex(0.1, -0.2)

example1

Let’s read the add function

Py_complex
_Py_c_sum(Py_complex a, Py_complex b)
{
    Py_complex r;
    r.real = a.real + b.real;
    r.imag = a.imag + b.imag;
    return r;
}

static PyObject *
complex_add(PyObject *v, PyObject *w)
{
    Py_complex result;
    Py_complex a, b;
    TO_COMPLEX(v, a); // check the type, covert to complex if type is not complex
    TO_COMPLEX(w, b);
    PyFPE_START_PROTECT("complex_add", return 0) // useless after version 3.7
    result = _Py_c_sum(a, b); // sum the complex
    PyFPE_END_PROTECT(result) // useless after version 3.7
    return PyComplex_FromCComplex(result);
}

The add operation is quite simple: sum the real parts, sum the imag parts, and return the new value.

The sub/divide/pow/neg operations are similar

>>> e = c + d
>>> repr(e)
'(0.1+0.8j)'

example2