我注意到当x
是整数时,rand(x)
会给我一个随机浮点数数组。 我想知道如何在特定范围内生成随机浮点类型变量的数组。 我尝试使用以下范围:
rand(.4:.6, 5, 5)
我得到的结果是:
0.4 0.4 0.4 0.4 0.4
0.4 0.4 0.4 0.4 0.4
0.4 0.4 0.4 0.4 0.4
0.4 0.4 0.4 0.4 0.4
0.4 0.4 0.4 0.4 0.4
如何获取范围而不是范围中的最低数?
也许更加优雅的方法是,由于您实际上想要从均匀分布中随机抽样,您可以使用Distribution
包:
julia> using Distributions
julia> rand(Uniform(0.4,0.6),5,5)
5×5 Array{Float64,2}:
0.547602 0.513855 0.414453 0.511282 0.550517
0.575946 0.520085 0.564056 0.478139 0.48139
0.409698 0.596125 0.477438 0.53572 0.445147
0.567152 0.585673 0.53824 0.597792 0.594287
0.549916 0.56659 0.502528 0.550121 0.554276
同样的方法也适用于从其他知名或用户定义的分布中进行抽样(只需将分布作为第一个参数传递给rand()
)
rand(.4:.1:.6, 5, 5)
.1
会为您的范围提供一步,这对于浮点数是必要的,对于增加1则不必要。问题在于,它会假定为1,而不考虑隐式精度。如果您需要更精确的增量,请执行以下操作:rand(.4:.0001:.6, 5, 5)
0.4587 0.557 0.586 0.4541 0.4686
0.4545 0.4789 0.4921 0.4451 0.4212
0.4373 0.5056 0.4229 0.5167 0.5504
0.5494 0.4068 0.5316 0.4378 0.5495
0.4368 0.4384 0.5265 0.5995 0.5231
julia> map(x->0.4+x*(0.6-0.4),rand(5,5))
5×5 Array{Float64,2}:
0.455445 0.475007 0.518734 0.463064 0.400925
0.509436 0.527338 0.566976 0.482812 0.501817
0.405967 0.563425 0.574607 0.502343 0.483075
0.50317 0.482894 0.54584 0.594157 0.528844
0.50418 0.515788 0.5554 0.580199 0.505396
julia> map( x -> start + x * (stop - start), rand(5,5) )
起始值为0.4,终止值为0.6。
你甚至可以通过让x从1到7(即1<x<7),来生成一个六面骰子,因为x恰好等于1.0或7.0的概率为零。
julia> map(x->Integer(floor(1+x*(7-1))),rand(5,5))
5×5 Array{Int64,2}:
2 6 6 3 2
3 1 3 1 6
5 4 6 1 5
3 6 5 5 3
3 4 3 5 4
julia> rand(1:6,5,5)
5×5 Array{Int64,2}:
3 6 3 5 5
2 1 3 3 3
1 5 4 1 5
5 5 5 5 1
3 2 1 5 6
只是另一个简单的解决方案(使用向量化操作)
0.2 .* rand(5,5) .+ 0.4
如果效率很重要...
@time 0.2 .* rand(10000, 10000) .+ 0.4
>> 0.798906 seconds (4 allocations: 1.490 GiB, 5.20% gc time)
@time map(x -> 0.4 + x * (0.6 - 0.4), rand(10000, 10000))
>> 0.836322 seconds (49.20 k allocations: 1.493 GiB, 7.08% gc time)
using Distributions
@time rand(Uniform(0.4, 0.6), 10000, 10000)
>> 1.310401 seconds (2 allocations: 762.940 MiB, 1.51% gc time)
@time rand(0.2:0.000001:0.4, 10000, 10000)
>> 1.715034 seconds (2 allocations: 762.940 MiB, 6.24% gc time)
eps()
作为步长参数,其值约为2.220446049250313e-16
。 - M. Thompson