Home >Backend Development >Python Tutorial >Detailed explanation of the principles and operations of floating point numbers in Python
This article mainly introduces the principles and operation analysis of floating point numbers in Python, analyzes common errors in Python floating point number operations in the form of examples, and briefly explains the principles of floating point number operations and implementation methods of comparison operations. Friends in need You can refer to the following
The examples in this article describe the principles and operations of floating point numbers in Python. I share it with you for your reference. The details are as follows:
Let’s first look at a counterintuitive example:
>>> s = 0. >>> for i in range(10): s += .1 >>> s 0.9999999999999999 # 错误被累加
Let’s look at another one that is more common and directly affects judgment. Logical example:
>>> from math import sqrt >>> a = sqrt(2) >>> a*a == a False
The reason why the above results occur is that Python (more precisely, the computer hardware architecture) represents floating-point numbers. Let’s take a look. The computer (based on binary) represents the decimal decimal 0.1. For the method of converting a decimal decimal to a binary decimal, please see Python Decimal Decimal and Binary Decimal Conversion. When converting decimal 0.1 to binary, the result is 0.0001100110011001...., an infinite loop. The computer cannot display infinite results and can only truncate the results. This is the root of the floating point precision problem.
“==” on floats
Based on the above considerations, when we perform equality comparisons of floating point numbers, we must be particularly careful and directly There is a problem with using ==. A common approach is not to test whether the floating point numbers are equal, but to test whether the two are close enough,
>>> a = sqrt(2) >>> abs(a*a-2) < epsilon # 判断是否小于某一小量
The above is the detailed content of Detailed explanation of the principles and operations of floating point numbers in Python. For more information, please follow other related articles on the PHP Chinese website!