gpt4 book ai didi

java - Math.pow(7,5) 与 7*7*7*7*7 不同——为什么?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:39:44 40 4
gpt4 key购买 nike

在做一个简单的 PRNG 项目时。我遇到了 Math.pow 的奇怪行为,只是将数字相乘。这是什么原因?我包括了 PRNG 类,以及我用来运行该程序的主类。如果比较结果,它开始时很好,但在第 3 次迭代时,乘法 PRNG 与 Math.pow() PRNG 不同。乘法 PRNG 也开始给出负数。它不应该。

public class PRNG {
int seed;
/**
* Creates a PRNG with the seed x0
*/
public PRNG(int x0){
this.seed = x0;
}

/**
* Return the next random number
*/
public int nextRand(){
//seed = (int) ((Math.pow(7, 5) * seed) % (Math.pow(2, 31) - 1));
seed = (int) ((7*7*7*7*7 * seed) % (Math.pow(2, 31) - 1));
return seed;
}

主要内容:

public class main {
final static int SEED = 1;

public static void main(String[] args) {
PRNG prng = new PRNG(SEED);

for(int i = 0; i < 100; i++){
System.out.println(prng.nextRand());
}
}

提前致谢!

最佳答案

这是因为您溢出了 seed 的 INT 值。

将您的代码更改为:

seed = (int) ((7*7*7*7*7 * (long)seed) % (Math.pow(2, 31) - 1));

解决问题。

关于java - Math.pow(7,5) 与 7*7*7*7*7 不同——为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19124546/

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