forked from zpoint/CPython-Internals
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplex.md
More file actions
77 lines (53 loc) · 1.87 KB
/
Copy pathcomplex.md
File metadata and controls
77 lines (53 loc) · 1.87 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# complex
# contents
* [related file](#related-file)
* [memory layout](#memory-layout)
* [example](#example)
# related file
* cpython/Objects/complexobject.c
* cpython/Include/complexobject.h
* cpython/clinic/complexobject.c.h
# memory layout
the **PyComplexObject** stores two double precision floating point number inside
the handling process and representation are mostly the same as [float](https://github.com/zpoint/CPython-Internals/blob/master/BasicObject/float/float.md) object

# example
```python3
c = complex(0, 1)
```

```python3
d = complex(0.1, -0.2)
```

let's read the add function
```c
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**, sum the **image** part and return the new value
the sub/divide/pow/neg operations are similar
```python3
>>> e = c + d
>>> repr(e)
'(0.1+0.8j)'
```
