同时做一个简单的PRNG项目。我偶然发现了Math.pow的奇怪行为,简单地将数字相乘。原因是什么?我已经包括了PRNG类,以及我用来运行程序的主类。如果您比较结果,它开始的很好,但在第三次迭代时,乘法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());
}
}
}
提前感谢!
发布于 2013-10-01 19:48:09
这是因为您正在溢出种子的INT值。
将代码更改为:
seed = (int) ((7*7*7*7*7 * (long)seed) % (Math.pow(2, 31) - 1));
解决问题。
发布于 2013-10-01 19:50:56
为了回答你问题的题目,没有什么不同。
public class MathPow {
public static void main(String[] args) {
testInt();
testLong();
}
private static void testInt(){
int a = 7*7*7*7*7;
int b = (int) Math.pow(7,5);
System.out.printf("a=%d b=%d (a==b)=%b\n", a, b, a==b);
}
private static void testLong(){
long a = 7*7*7*7*7;
long b = (long) Math.pow(7,5);
System.out.printf("a=%d b=%d (a==b)=%b\n", a, b, a==b);
}
}
产生的输出:
a=16807 b=16807 (a==b)=true
a=16807 b=16807 (a==b)=true
发布于 2013-10-01 20:08:28
为了解决你关心的行为,而不是你的帖子标题:
评价步骤:
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));
展示:
public class MathPow {
static int seed=1;
public static void main(String[] args) {
System.out.println("7*7*7*7*7");
whatType(7*7*7*7*7);
whatType(7*7*7*7*7*seed);
whatType(Math.pow(2,31));
whatType(Math.pow(2,31)-1);
whatType(((7*7*7*7*7 * seed) % (Math.pow(2, 31) - 1)));
System.out.println("Math.pow(7,5)");
whatType(Math.pow(7,5));
whatType(Math.pow(7,5) * seed);
whatType(Math.pow(2,31));
whatType(Math.pow(2,31)-1);
whatType((Math.pow(7, 5) * seed) % (Math.pow(2, 31) - 1));
}
private static void whatType(Object o){
System.out.println(o.getClass());
}
}
输出:
7*7*7*7*7
class java.lang.Integer
class java.lang.Integer
class java.lang.Double
class java.lang.Double
class java.lang.Double
Math.pow(7,5)
class java.lang.Double
class java.lang.Double
class java.lang.Double
class java.lang.Double
class java.lang.Double
https://stackoverflow.com/questions/19124546
复制相似问题