Reputation: 437
I have done a program that must output a file with values of a function. This function produce very large values but I only need the logarithm, which can go up to values of around 10000 or even a million (large, but manageable with integer 32 bit variables).
Now, obviously the function itself will be of the order of exp(10000)
and that's huge. So I'm looking for any tricks to calculate the logarithm. I'm using python since I thought that it's native support for very large numbers would be useful, but it's not in the cases of very large numbers.
The value of the function is calculated as:
a*(x1+x2+x3+x4)
and I have to take the logarithm of that. I already preprocess the logarithms of all factors and then sum them all, but I can't do anything (at least anything simple) with log(x1+x2+x3+x4)
.
The results from python ar NaN because the x1,x2,x3,x4 variable grow to much. They are calculated as:
x = [1,1,1,1]
for i in range(1,K):
x[j] *= a*cosh(b*g[i]) # even values of i
x[j] *= a*sinh(b*g[i]) # odd values of i
for some constants a
, b
and a vector g[]
. That's just pseudo code, I write each x[1], x[2].
Is there any trick by which I could calculate the logarithm of that sum without running into the NaN
problem?
Thank you very much
P.S.: I was using python because of what I said, if there's any special library for C(++) or something like that to deal with very large numbers, I would really appreciate it.
P.S.: The constant b
inside the cosh
can be of the order of 100 and than can make things blow up, so if there's anything to do with taking that constant out somehow...
Upvotes: 1
Views: 2202
Reputation: 4209
Scaling the summands like this:
x = []
scale_factor = max(b*g[i] for i in range(1, K))
for i in range(1, K):
x[i] = cosh(b*g[i] - scale_factor)
result = log(a)*K + sum(log(x[i]) for i in range(1, K)) + log(scale_factor)
edit: uh-oh, one detail is wrong:
result = log(a)*K + sum(log(x[i]) for i in range(1, K)) + scale_factor
The last term is just the factor, not it's log. Sorry.
Upvotes: 1
Reputation: 496
I see that in your loop you are each time multiplying each x with a constant a. If you skip that factor, and take log(x1+x2+x3+x4) which may then be manageable, you just add log(a) to that to get the final result. Or n*log(a) if you're multiplying by a several times.
That idea is language independent. :-)
Upvotes: 1