Dry Goods Collection | Python implements floating point operations

Insert picture description here
The computer intelligently handles the operations of countable sets, but all real numbers are uncountable, so the computer can only use some strange methods to fit it, so floating-point numbers are produced. We all know that floating-point numbers lack precision. A common problem with floating-point numbers is that they cannot accurately represent decimal numbers.
(1) Floating-point number error
A common problem with floating-point numbers is that in the computer world, floating-point numbers cannot accurately represent decimal. Moreover, even the simplest mathematical operations can bring uncontrollable consequences. Because in the computer world, only 0 and 1 are recognized.

x = 4.20
y = 2.10
x + y
6.3000000000000007

(x + y) == 6.3
False

x = 1.2
y = 2.3
x + y
3.5

(x + y) == 3.5
True The
above-mentioned problems come from the way the computer's cpu and floating-point numbers are expressed, and we cannot control it at the code level. In some occasions that need to accurately represent floating-point numbers, such as financial settlement, these errors are unacceptable.
(2) Decimal module for decimal mathematical calculations
The decimal module in python can solve the above troubles. In the decimal module, decimal.Decimal objects can be constructed by integers, strings or principles. If it is a floating-point number, pay special attention to the fact that there is an error in the floating-point number itself, and you need to convert the floating-point number to a string first.

from decimal import Decimal
from decimal import getcontext
Decimal(‘4.20’) + Decimal(‘2.10’)
Decimal(‘6.30’)

from decimal import Decimal
from decimal import getcontext
x = 4.20
y = 2.10
z = Decimal(str(x)) + Decimal(str(y))
z
Decimal(‘6.3’)

getcontext().prec = 4 #Set the precision
Decimal('1.00') /Decimal('3.0')
Decimal('0.3333')

Of course, while the accuracy is improved, it will definitely bring a loss of performance. In occasions that require extremely precise data (such as financial settlement), these performance losses are worthwhile. But if it is a large-scale scientific calculation, operating efficiency needs to be considered. After all, the native float is definitely much faster than the Decimal object.

Part of the content of the article comes from the Internet, contact intrusion and deletion* The
article reference comes from http://http.taiyangruanjian.com/news/54873.html

Guess you like

Origin blog.csdn.net/zhimaHTTP/article/details/111932125