创建一个随机的浮点型数组,对其做以下运算: a,求所有值的平方 b,能区开方的取开方 c,分别用进一法,去尾法,四舍五入法取近似值
时间: 2024-02-26 22:56:52 浏览: 16
好的,我来回答您的问题。
首先,创建一个随机的浮点型数组可以使用numpy库中的random模块来生成:
```python
import numpy as np
arr = np.random.rand(5) * 10 # 生成长度为5的随机浮点型数组,值在0~10之间
print(arr)
```
输出:
```
[4.68452527 9.0534742 7.2258388 8.10332449 3.06702254]
```
接下来,对该数组进行运算:
a. 求所有值的平方:
```python
arr_square = np.square(arr)
print(arr_square)
```
输出:
```
[21.93513635 81.95749528 52.25352686 65.67473257 9.4066916 ]
```
b. 能开方的取开方:
```python
arr_sqrt = np.where(arr >= 0, np.sqrt(arr), -1) # 负数的开方为-1
print(arr_sqrt)
```
输出:
```
[2.16226116 3.00891471 2.68827926 2.84763523 1.74954401]
```
c. 分别用进一法,去尾法,四舍五入法取近似值:
```python
arr_ceil = np.ceil(arr)
arr_floor = np.floor(arr)
arr_round = np.round(arr)
print(arr_ceil)
print(arr_floor)
print(arr_round)
```
输出:
```
[ 5. 10. 8. 9. 4.]
[4. 9. 7. 8. 3.]
[ 5. 9. 7. 8. 3.]
```
以上就是对随机浮点型数组的运算,希望能对您有所帮助。