Math Overflow -- Handling Large Numbers
I am having a problem handling large numbers.
I need to calculate the log of a very large number. The number is the product of a series of numbers. For example: log(2x3x66x435x444) though my actual series are longer.
I am getting a math overflow because product grows very large, very quickly.
开发者_Go百科Are there special math libraries to handle huge numbers? Any ideas how I can solve this?
There is a neat mathematical solution to this problem.
Rather than obtaining the product of a series by multiplying each number, you can use their log values. The noted principle is:
log(a*b) = log(a) + log(b)
For the example series (2, 3, 66, 435, 444), the brute-force product is calculated as 2 * 3 * 66 * 435 * 44 = 76,483,440.
However, you can also obtain the product from the sum of the logs. For a series (n1, n2, n3, n4,...) the product of the series is: 10 ^ (log(n1) + log(n2) + log(n3) + log(n4)...)
log(2) = 0.30103
log(3) = 0.47712
log(66) = 1.8195
log(435) = 2.6384
log(444) = 2.6474
The sum of the values is roughly 7.8835. The product of the series is 10 ^ 7.8835 (76,483,440).
Since you're looking for the log of the product of the series, just the sum of the individual log() values, 7.8835. That's it.
Um: log(a*b) = log(a) + log(b)
Use Python ;)
$python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.log(2*3*66*435*444)
18.15258480477539
>>>
Java classes BigInteger and BigDecimal can help
http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html
http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html
精彩评论