Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum very large numbers to 1 in python

Tags:

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.

like image 550
Joao Caetano Avatar asked Nov 21 '17 17:11

Joao Caetano


1 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.)

like image 179
tobias_k Avatar answered Sep 19 '22 12:09

tobias_k