Reputation: 259
I want to calculate additions of a very large number (type, float) and a very small number using Python 2.7.
For example:
>> x = 1546439400046560970.
>> y = 1.
>> print(int(x + y))
1546439400046561024
This is not right. Correct answer is 1546439400046560971.
I realize that the problem is due to type cast from float to int. How could I solve this problem, if I want to get the correct answer?
Upvotes: 1
Views: 47
Reputation: 76254
I realize that the problem is due to type cast from float to int.
Not really. The float itself does not store your value precisely. You can prove that this is the case by converting to a type that has more precision than a float, for example decimal
.
>>> import decimal
>>> decimal.decimal(1546439400046560971.)
Decimal('1546439400046561024')
So any solution that initially stores x
as a float is doomed to fail, even if you never use the int
type.
One possible solution is to store your values as decimals to begin with. Remember to initialize them using strings and not floats, or else the precision will be lost.
>>> from decimal import Decimal
>>> x = Decimal("1546439400046560971")
>>> y = Decimal("1")
>>> x+y
Decimal('1546439400046560972')
Upvotes: 2