[英]High power and double precision
How do you solve the below equation in some programming language of your choice? 您如何用自己选择的某种编程语言来求解以下方程式?
(1-1/X)^Y
Easy! 简单!
But how about when X & Y are very big and X>>Y 但是当X&Y很大并且X >> Y时怎么样
eg 例如
(1-1/X)^Y
where
X = 10^40
Y = 10^12
Looks like it should be a simple enough problem, but getting around the double precision problem before applying the power is something I was not able to figure out. 看起来这应该是一个足够简单的问题,但是在应用电源之前解决双精度问题是我无法弄清楚的。
Well, (1 - 1/X)^Y = exp(Y*log(1 - 1/X))
. 好吧, (1 - 1/X)^Y = exp(Y*log(1 - 1/X))
。 If X
is very large, and much larger than Y
, you can approximate the logarithm with 如果X
非常大,并且比Y
大得多,则可以用
log(1 - 1/x) = -1/x -1/(2*X^2) + O(1/X^3)
and calculate 并计算
exp(-(Y/X+ Y/(2*X*X)))
If X
isn't that much larger than Y
, using a third or even fourth term of the Taylor series of the logarithm may be necessary. 如果X
不比Y
大很多,则可能需要使用对数的泰勒级数的第三项或第四项。
Using GNU Octave the calculations are approximate: 使用GNU Octave进行的计算是近似的:
octave:1> x = 10^40
x = 1.0000e+40
octave:2> y = 10^12
y = 1.0000e+12
octave:3> (1-1/x)^y
ans = 1
octave:8> exp(-(y/x + y /(2*x*x)))
ans = 1
Provided that the calculation made by Daniel Fischer is correct, the code to calculate exp(-(Y/X+ Y/(2*X*X)))
in Java using BigDecimal is: 假设Daniel Fischer进行的计算是正确的,则使用BigDecimal在Java中计算exp(-(Y/X+ Y/(2*X*X)))
的代码为:
public static void main(String[] args) {
BigDecimal x = new BigDecimal(10,MathContext.UNLIMITED).pow(40);
BigDecimal y = new BigDecimal(10,MathContext.UNLIMITED).pow(12);
BigDecimal twoXSquared = new BigDecimal(2,MathContext.UNLIMITED).multiply(x).multiply(x);
BigDecimal yDividedByTwoXSquared = y.divide(twoXSquared);
BigDecimal yDividedByX = y.divide(x);
BigDecimal exponent = new BigDecimal(-1,MathContext.UNLIMITED).multiply(yDividedByX.add(yDividedByTwoXSquared));
System.out.println(exponent.toEngineeringString());
BigDecimal result = new BigDecimal(Math.E,MathContext.UNLIMITED).pow(exponent.intValue());
System.out.println(result.toEngineeringString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.