采取模数双NUmber [英] Taking Modulo of Double NUmber
问题描述
我已经给了两个数字 a
和 b
。我必须计算(a ^ b)%1000000007
。如何计算浮点数。例如:
I have given two number a
and b
.I have to Calculate (a^b)%1000000007
.How Can i calculate for floating point numbers. Ex:
a= 7.654 and b=10000
这是我的代码将%
工作:
public static double super_pow(double A , long B){
double o=1;
while(B>0){
if((B&1)!=0) o*=A;
A*=A;
B/=2;
o%=mod;
A%=mod;
}
return (o)%mod;
}
推荐答案
是的,在Java中在浮点类型上使用%运算符。
Yes, in Java you can use the % operator on floating point types.
尽管如此,您将会遇到指数问题:您不能使用%
以减少中间结果,因为模数不分布在浮点乘数上:(a * b)%c
不是(a%c) *(b%C)
。如果您尝试直接计算7.654 ^ 10000,您将获得无限远
;它超过 double
的最大值。即使没有,也不能相信结果的最低位数,因为它们是通过舍入和表示错误而产生的纯噪声。
You will have problems with the exponent though: You can't use %
to reduce the intermediate results because modulo does not distribute over floating point multiplication: (a*b)%c
is not (a%c)*(b%c)
. If you try to compute 7.654^10000 directly you will get infinity
; it exceeds the maximum value for double
. Even if it didn't you couldn't trust the lowest digits of the result because they are pure noise created by rounding and representation error.
您可以使用实现精确算术的库,例如java.math.BigDecimal,但这在执行时间和内存方面花费很多。如果你认为你需要做这个计算作为一个更大的问题的一部分,可能你应该退一步,找到另一种方式。
You could use a library that implements exact arithmetic, such as java.math.BigDecimal, but that will cost a lot in terms of execution time and memory. If you think you need to do this calculation as a part of a bigger problem, probably you should take a step back and find another way.
编辑: / strong>以下是 BigDecimal
的结果:
BigDecimal[] divmod = new BigDecimal("7.654").pow(10000)
.divideAndRemainder(new BigDecimal("1000000007"))
return divmod[1].doubleValue() // I get 9.01287592373194E8
这篇关于采取模数双NUmber的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!