简体   繁体   中英

How to accurately interpret large float numbers in Python

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?

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM