numpy.linspace是否可以生成幾乎等距且不應該與輸出完全相同的亂數
我查看了該numpy.random.uniform函式,但它沒有給出所需的結果。
此外,該函式生成的值的總和應該與 numpy.linspace 函式生成的值的總和相同。
代碼
import random
import numpy as np
random.seed(42)
data=np.random.uniform(2,4,10)
print(data)
uj5u.com熱心網友回復:
您可以考慮在numpy.linspace. 將這些數字設定為正態分布的平均值并將方差設定得不太高將生成接近 的輸出的數字numpy.linspace。例如,
>>> import numpy as np
>>> exact_numbers = np.linspace(2.0, 10.0, num=5)
>>> exact_numbers
array([ 2., 4., 6., 8., 10.])
>>> approximate_numbers = np.random.normal(exact_numbers, np.ones(5) * 0.1)
>>> approximate_numbers
array([2.12950013, 3.9804745 , 5.80670316, 8.07868932, 9.85288221])
uj5u.com熱心網友回復:
也許這個技巧通過結合和numpy.linspace幫助你:(你可以改變亂數的大小)numpy.random.uniformrandom choice two indexes and increase one of them and decrease othersize=10threshold=0.1
import numpy as np
size = 10
theroshold = 0.1
r = np.linspace(2,4,size) # r.sum()=30
# array([2. , 2.22222222, 2.44444444, 2.66666667, 2.88888889,
# 3.11111111, 3.33333333, 3.55555556, 3.77777778, 4. ])
c = np.random.uniform(0,theroshold,size)
# array([0.02246768, 0.08661081, 0.0932445 , 0.00360563, 0.06539992,
# 0.0107167 , 0.06490493, 0.0558159 , 0.00268924, 0.00070247])
s = np.random.choice(range(size), size 1)
# array([5, 5, 8, 3, 6, 4, 1, 8, 7, 1, 7])
for idx, (i,j) in enumerate(zip(s, s[1:])):
r[i] = c[idx]
r[j] -= c[idx]
print(r)
print(r.sum())
輸出:
[2. 2.27442369 2.44444444 2.5770278 2.83420567 3.19772192
3.39512762 3.50172642 3.77532244 4. ]
30
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/487609.html
