gpt4 book ai didi

java - 矩阵中的随机值,如何以给定的概率设置它们?

转载 作者:行者123 更新时间:2023-12-02 06:35:55 25 4
gpt4 key购买 nike

我有这个代码:

import java.util.Random;

public class Vectors {

public static int[][] vectors() {
return vectors(200,150,12345);
}

// the function creates an array of vectors
// size is the number of vectors
// dim is the dimension
// seed is for the random number generator
//
public static int[][] vectors(int size, int dimension, int seed) {

Random rng = new Random(seed);
int[][] answer = new int[size][dimension];

for(int i=0; i<size; i++) {
for(int j=0; j<dimension; j++) {
answer[i][j] = rng.nextInt(20) - 10;
}
}

return answer;
}

}

我必须构建一个 50 列 x 150 行的随机矩阵 M。矩阵中的值为{-1/√ 50, 1/√ 50},每个值出现的概率为50%。

我如何通过帮助下面的代码来做到这一点?

最佳答案

对于您需要生成的每个数字,执行以下操作:

  • 生成 0 到 99(含)之间的随机数。
  • 如果数字 < 50,则使用第一个值
  • 否则使用第二个值。

该算法可以应用于所有整数百分比值,并且可以轻松扩展到两个以上的选项。

当然,在您的特定情况下,您可以简化算法以生成 0 到 1(含)之间的随机数,因为您只有 2 个同等权重的选项,但我上面显示的选项是更通用的选项(甚至更一般的是使用 0 到 1(不包括)之间的 float 。

关于java - 矩阵中的随机值,如何以给定的概率设置它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19654863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com