How to sum very large numbers to 1 in python

Viewed 2677

So imagine I have

>>> a = 725692137865927813642341235.00

If I do

>>> sum = a + 1

and afterwards

>>> sum == a
True

This is because a is bigger than a certain threshold.

Is there any trick like the logsumexp to perform this?

PS: a is an np.float64.

3 Answers

If a has to be specifically of type float, no, then that's not possible. In fact, the imprecision is much greater:

>>> a = 725692137865927813642341235.00
>>> a + 10000 == a
True

However, there are other data types that can be used to represent (almost) arbitrary precision decimal values or fractions.

>>> d = decimal.Decimal(a)
>>> d + 1 == d
False
>>> f = fractions.Fraction(a)
>>> f + 1 == f
False

(Note: of course, doing Decimal(a) or Fraction(a) does not magically restore the already lost precision of a; if you want to preserve that, you should pass the full value as a string.)

0) import decimal
1) setup appropriate precision of the decimal.getcontext() ( .prec attribute )
2) declare as decimal.Decimal() instance

>>> import decimal
>>> decimal.getcontext().prec
28
>>> decimal.getcontext().prec = 300
>>> dec_a = decimal.Decimal( '725692137865927813642341235.0' )

It is a pleasure to use decimal module for extremely extended numerical precision solvers.


BONUS:

Decimal module has very powerful context-methods, that preserve the decimal-module's strengths .add(), .subtract(), .multiply(), .fma(), .power() so as to indeed build an almost-infinite precision solver methods ...

Definitely worth mastering these decimal.getcontext() methods - your solvers spring into another league in precision and un-degraded convergence levels.

Will dividing a by 100,000 then adding 1 then times it back up again? Eg.

a=725692137865927813642341235.00
a /= 100000
a += 0.00001
a *= 100000
Related