如何在 (-1, 1) 范围内生成随机值以使总和为 0? [英] How to generate random values in range (-1, 1) such that the total sum is 0?

查看:38
本文介绍了如何在 (-1, 1) 范围内生成随机值以使总和为 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果总和为 1,我可以将这些值除以它们的总和.但是,当总和为 0 时,这种方法不适用.

If the sum is 1, I could just divide the values by their sum. However, this approach is not applicable when the sum is 0.

也许我可以计算我采样的每个值的相反数,所以我总是有一对数字,这样它们的总和为 0.但是这种方法减少了我希望在我的随机数组中拥有的随机性".

Maybe I could compute the opposite of each value I sample, so I would always have a pair of numbers, such that their sum is 0. However this approach reduces the "randomness" I would like to have in my random array.

有更好的方法吗?

数组长度可以变化(从 3 到几百个),但必须在采样前固定.

the array length can vary (from 3 to few hundreds), but it has to be fixed before sampling.

推荐答案

您可以使用 sklearns Standardscaler.它会缩放您的数据,使其方差为 1,平均值为 0.0 的平均值等于 0 的总和.

You could use sklearns Standardscaler. It scales your data to have a variance of 1 and a mean of 0. The mean of 0 is equivalent to a sum of 0.

from sklearn.preprocessing import StandardScaler, MinMaxScaler
import numpy as np
rand_numbers = StandardScaler().fit_transform(np.random.rand(100,1, ))

如果您不想使用 sklearn,您可以手动标准化,公式非常简单:

If you don't want to use sklearn you can standardize by hand, the formula is pretty simple:

rand_numbers = np.random.rand(1000,1, )
rand_numbers = (rand_numbers - np.mean(rand_numbers)) / np.std(rand_numbers)  

这里的问题是 1 的方差,这会导致数字大于 1 或小于 -1.因此,您将数组按其最大 abs 值进行划分.

The problem here is the variance of 1, that causes numbers greater than 1 or smaller than -1. Therefor you devide the array by its max abs value.

rand_numbers = rand_numbers*(1/max(abs(rand_numbers)))

现在您有一个数组,其值介于 -1 和 1 之间,总和非常接近于零.

Now you have an array with values between -1 and 1 with a sum really close to zero.

print(sum(rand_numbers))
print(min(rand_numbers))
print(max(rand_numbers))

输出:

[-1.51822999e-14]
[-0.99356294]
[1.]

使用此解决方案,您的数据中将始终是一 1 或一 -1.如果您想避免这种情况,您可以通过最大绝对值向除法添加一个正随机因子.rand_numbers*(1/(max(abs(rand_numbers))+randomfactor))

What you will have with this solution is either one 1 or one -1 in your data allways. If you would want to avoid this you could add a positive random factor to the division through the max abs. rand_numbers*(1/(max(abs(rand_numbers))+randomfactor))

编辑

正如@KarlKnechtel 提到的,除以标准差与除以最大绝对值是多余的.

As @KarlKnechtel mentioned the division by the standard deviation is redundant with the division by max absolute value.

以上可以简单地通过:

rand_numbers = np.random.rand(100000,1, )
rand_numbers = rand_numbers - np.mean(rand_numbers)
rand_numbers = rand_numbers / max(abs(rand_numbers))

这篇关于如何在 (-1, 1) 范围内生成随机值以使总和为 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆