forked from zpoint/CPython-Internals
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplex_cn.md
More file actions
75 lines (52 loc) · 1.82 KB
/
Copy pathcomplex_cn.md
File metadata and controls
75 lines (52 loc) · 1.82 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
# complex
# 目录
* [相关位置文件](#相关位置文件)
* [内存构造](#内存构造)
* [示例](#示例)
# 相关位置文件
* cpython/Objects/complexobject.c
* cpython/Include/complexobject.h
* cpython/clinic/complexobject.c.h
# 内存构造
**PyComplexObject** 内部存储了两个双精度浮点数, 处理过程和表示方法都和 [float](https://github.com/zpoint/CPython-Internals/blob/master/BasicObject/float/float_cn.md) 对象很类似

# 示例
```python3
c = complex(0, 1)
```

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

我们来读下加法部分的代码
```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); // 检查下类型, 如果不为 PyComplexObject 需要先转换为 PyComplexObject
TO_COMPLEX(w, b);
PyFPE_START_PROTECT("complex_add", return 0) // 在 3.7 版本之后就没用了
result = _Py_c_sum(a, b); // sum the complex
PyFPE_END_PROTECT(result) // 在 3.7 版本之后就没用了
return PyComplex_FromCComplex(result);
}
```
加法看起来比较简单, 把实数 **real** 部分相加, 把虚数 **imag** 部分相加, 并返回相加后的整个结构
加减乘数, 负号, 平方等操作都很类似
```python3
>>> e = c + d
>>> repr(e)
'(0.1+0.8j)'
```
