np.random.rand()
是NumPy库中的函数,用于生成在[0, 1)区间内均匀分布的随机数,可以接受多个整数参数,用于指定生成数组的形状。
- 生成一个随机标量:
import numpy as np
random_scalar = np.random.rand()
print(random_scalar)
print(type(random_scalar))
0.20409991617026446
<class 'float'>
- 生成一个一维随机数组:
random_array_1d = np.random.rand(5)
print(random_array_1d)
print(type(random_array_1d))
[3.83063651e-01 3.37696745e-01 3.25521541e-04 1.02174830e-01
1.52260494e-01]
<class 'numpy.ndarray'>
- 生成一个二维随机数组:
random_array_2d = np.random.rand(3, 4)
print(random_array_2d)
print(type(random_array_2d))
[[0.17820633 0.07469565 0.06193551 0.62990055]
[0.70111109 0.40806394 0.4081677 0.22036044]
[0.22977401 0.82057856 0.61116728 0.78780622]]
<class 'numpy.ndarray'>
- 生成一个多维随机数组:
random_array_3d = np.random.rand(2, 3, 4)
print(random_array_3d)
print(type(random_array_3d))
[[[0.74992816 0.75239264 0.11692434 0.9777651 ]
[0.59274321 0.18457437 0.17713543 0.76506547]
[0.2457787 0.32004618 0.53218236 0.85916077]]
[[0.926343 0.52791838 0.40831638 0.83245913]
[0.17422364 0.09666104 0.24919322 0.50269557]
[0.02559896 0.42326947 0.79123465 0.47684072]]]
<class 'numpy.ndarray'>
- 在其他区间生成随机数,例如,在[a, b)区间生成随机数:
a = 5
b = 10
random_array = a + (b-a) * np.random.rand(3, 4)
print(random_array)
[[5.36916413 7.84348256 7.30944149 9.38041737]
[6.19994777 5.09849038 9.84603643 7.90837064]
[5.78437168 6.75113295 5.81087402 6.28795399]]