【问题标题】:How do I fix modulus in Linear Congruential Generator?如何在线性同余生成器中修复模量?
【发布时间】:2015-11-15 12:01:08
【问题描述】:

我的线性同余生成器有一个问题。我有两个模数。如果我替换或删除其中任何一个,我不会得到任何输出,除了在最后启动的计数器,但如果没有使用计数器处理的输出,这将毫无用处。

我需要应用程序输出 0 到 9 范围内的数字,然后在最后输出数字的分布。这是我的代码:

public static void main(String[] args) {
  int fact;
  int constant;
  int modulus;
  int seed;

  Scanner scan = new Scanner(System.in);

  System.out.println("Input fact: ");
  fact = scan.nextInt();

  System.out.println("Input constant: ");
  constant = scan.nextInt();

  System.out.println("Input modulus: ");
  modulus = scan.nextInt();

  System.out.println("Input seed: ");
  seed = scan.nextInt();

  int[] arrayBox;
  arrayBox = new int[10];

  for (int i = 0; i < 10; i++) {

    seed = (seed * fact + constant) % modulus; // First modulus

    System.out.println(seed);
    arrayBox[seed % 10] = arrayBox[seed % 10] + 1; // Second modulus
  }

  for (int i = 0; i < 10; i++) {
    System.out.print(+(100 * arrayBox[i] / 10) + "% ");
  }
}

有什么方法可以绕过第二个模数,并且仍然让我的输出和计数器在我想要的范围内(0 到 9)工作?

【问题讨论】:

    标签: java random generator modulus


    【解决方案1】:

    我在执行您的操作时遇到了一些麻烦,但我认为最后是您想要的:

    System.out.println(i + ":\t" + (100*arrayBox[i]/10) + "%");
    

    请注意,此程序不会将实际的 seed 值保存在任何地方,因此您将无法查看它们。

    以下是该程序的示例运行,其中包含一些合理的输入参数值:

    Input fact: 
    257
    Input constant: 
    31
    Input modulus: 
    64
    Input seed: 
    89
    56
    23
    54
    21
    52
    19
    50
    17
    48
    15
    0:  10%
    1:  10%
    2:  10%
    3:  10%
    4:  10%
    5:  10%
    6:  10%
    7:  10%
    8:  10%
    9:  10%
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-22
      • 2013-10-09
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多