Python:math
lastmod 2023-01-05created 2015-12-176 edits
Example
Checking whether two floating-point numbers are equal
0.1 + 0.2 is 0.30000000000000004, so it differs from 0.3. The problem that arises from representing real numbers as approximations like this is called floating-point rounding error. So when comparing floating-point numbers, you should take the difference between the computed value and the value to compare against and check whether it is less than or equal to sys.float_info.epsilon.
The value of x, 0.30000000000000004, minus 0.3 is less than or equal to sys.float_info.epsilon, so the two values can be considered equal. In particular, using math.fabs to take the absolute value of the difference lets the check work correctly even if the difference is negative.
The value stored in sys.float_info.epsilon is called machine epsilon. When a real number is rounded to the nearest floating-point number, the relative error is always at most machine epsilon. In other words, machine epsilon is the upper bound of the rounding error, and if the difference between the computed value and the value to compare against is less than or equal to machine epsilon, the two numbers can be considered equal.
isclose
From Python 3.5 onward, you can use the math.isclose function to check whether two floating-point numbers are equal.
fabs
Floating-point absolute value
Exact decimal places with Decimal
To use fixed-point numbers without rounding error, use Decimal from the decimal module. Decimal handles numbers in base 10 and represents decimal places exactly.
See Python:decimal#Decimal for details.
Representing fractions with Fraction
Repeating decimals cannot be represented exactly even with fixed-point numbers. In that case, use Fraction from the fractions module to represent them as fractions.
>>> from fractions import Fraction
>>> Fraction('10/3') # 10을 3으로 나누면 순환소수 3.33333...이지만 분수 3분의 10으로 표현
Fraction(10, 3)
See Python:fractions#Fraction for details.