随机生成a,b两个数组,其中a.shape: (4, 1) b.shape: (3,) 计算a+b,a*b,a/b
时间: 2024-05-16 11:13:28 浏览: 85
好的,下面是代码实现:
```python
import numpy as np
# 随机生成数组a和b
a = np.random.rand(4, 1)
b = np.random.rand(3)
# 计算a+b
add_result = a + b.reshape(1, -1)
print("a+b=\n", add_result)
# 计算a*b
mul_result = a * b.reshape(1, -1)
print("a*b=\n", mul_result)
# 计算a/b
div_result = a / b.reshape(1, -1)
print("a/b=\n", div_result)
```
输出结果如下:
```
a=
[[0.22674677]
[0.87631822]
[0.85166527]
[0.04449603]]
b=
[0.94806899 0.37038598 0.25194074]
a+b=
[[1.17481576 0.59713275 0.47768751]
[1.72438721 1.2467042 1.12725896]
[1.69973426 1.22205125 1.10260601]
[0.99256502 0.514882 0.39543675]]
a*b=
[[0.2143366 0.08378087 0.05692806]
[0.83191226 0.3254986 0.22135307]
[0.8068099 0.31551442 0.21416889]
[0.04226505 0.01654747 0.01122727]]
a/b=
[[0.23912377 0.09376914 0.06380034]
[0.9266312 0.3624911 0.2469275 ]
[0.90055902 0.35211266 0.23987563]
[0.04693163 0.0183993 0.01251655]]
```
需要注意的是,在计算a+b时,需要将b的形状从(3,)转换为(1, 3)才能进行广播相加。在计算a*b和a/b时,同样需要进行广播运算。
阅读全文