Files
ailearning/docs/da/043.md
2020-10-19 21:08:55 +08:00

241 lines
2.7 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 二元运算
In [1]:
```py
import numpy as np
```
## 四则运算
| 运算 | 函数 |
| --- | --- |
| `a + b` | `add(a,b)` |
| `a - b` | `subtract(a,b)` |
| `a * b` | `multiply(a,b)` |
| `a / b` | `divide(a,b)` |
| `a ** b` | `power(a,b)` |
| `a % b` | `remainder(a,b)` |
以乘法为例,数组与标量相乘,相当于数组的每个元素乘以这个标量:
In [2]:
```py
a = np.array([1,2])
a * 3
```
Out[2]:
```py
array([3, 6])
```
数组逐元素相乘:
In [3]:
```py
a = np.array([1,2])
b = np.array([3,4])
a * b
```
Out[3]:
```py
array([3, 8])
```
使用函数:
In [4]:
```py
np.multiply(a, b)
```
Out[4]:
```py
array([3, 8])
```
事实上,函数还可以接受第三个参数,表示将结果存入第三个参数中:
In [5]:
```py
np.multiply(a, b, a)
```
Out[5]:
```py
array([3, 8])
```
In [6]:
```py
a
```
Out[6]:
```py
array([3, 8])
```
## 比较和逻辑运算
| 运算 | 函数< |
| --- | --- |
| `==` | `equal` |
| `!=` | `not_equal` |
| `>` | `greater` |
| `>=` | `greater_equal` |
| `<` | `less` |
| `<=` | `less_equal` |
| | `logical_and` |
| | `logical_or` |
| | `logical_xor` |
| | `logical_not` |
| `&` | `bitwise_and` |
| | `bitwise_or` |
| `^` | `bitwise_xor` |
| `~` | `invert` |
| `>>` | `right_shift` |
| `<<` | `left_shift` |
等于操作也是逐元素比较的:
In [7]:
```py
a = np.array([[1,2,3,4],
[2,3,4,5]])
b = np.array([[1,2,5,4],
[1,3,4,5]])
a == b
```
Out[7]:
```py
array([[ True, True, False, True],
[False, True, True, True]], dtype=bool)
```
这意味着,如果我们在条件中要判断两个数组是否一样时,不能直接使用
```py
if a == b:
```
而要使用:
```py
if all(a==b):
```
对于浮点数,由于存在精度问题,使用函数 `allclose` 会更好:
```py
if allclose(a,b):
```
`logical_and` 也是逐元素的 `and` 操作:
In [8]:
```py
a = np.array([0,1,2])
b = np.array([0,10,0])
np.logical_and(a, b)
```
Out[8]:
```py
array([False, True, False], dtype=bool)
```
`0` 被认为是 `False`,非零则是 `True`
比特操作:
In [9]:
```py
a = np.array([1,2,4,8])
b = np.array([16,32,64,128])
a | b
```
Out[9]:
```py
array([ 17, 34, 68, 136])
```
取反:
In [10]:
```py
a = np.array([1,2,3,4], np.uint8)
~a
```
Out[10]:
```py
array([254, 253, 252, 251], dtype=uint8)
```
左移:
In [11]:
```py
a << 3
```
Out[11]:
```py
array([ 8, 16, 24, 32], dtype=uint8)
```
要注意的是 `&` 的运算优先于比较运算如 `>` 等,所以必要时候需要加上括号:
In [12]:
```py
a = np.array([1,2,4,8])
b = np.array([16,32,64,128])
(a > 3) & (b < 100)
```
Out[12]:
```py
array([False, False, True, False], dtype=bool)
```