_

Always be tactful

Insights (종료)/For EN

[CS] 1.1 + 0.1 != 1.2, Why?

funczun 2024. 12. 13. 12:13
How are floating-point numbers stored in a computer?

 Computers represent all information in binary. Floating-point numbers are also converted to binary and stored in RAM, but during this process, some of the value is lost, resulting in an approximation rather than the exact value.

 For example, when you convert 0.1 to binary, it becomes a repeating decimal: 0.00011001100110011... which continues infinitely. Since a single number is typically stored using 32 bits, the trailing part is truncated, leading to a small error. As a result, the value that is actually stored might be something like 0.10000000000000000555..., introducing a tiny error.


▶ Use the double data type.

 In C, you can use the double data type, which allocates 64 bits for each number, significantly reducing the error. However, this comes with the downside of requiring twice the memory. (In Python, the float type is inherently handled as a 64-bit floating-point number.)


Allow a small margin of error.

 This method allows for a small margin of error, considering the numbers are very close, and if the difference is smaller than a given threshold, they are considered equal.

epsilon = 1e-9
abs((1.1 + 0.1) - 1.2) < epsilon  # True

 

Convert to integers and calculate.

 For example, you can multiply 1.1 and 0.1 by 10 to convert them into integers, perform the calculation, and then divide by 10 afterward. This avoids errors but can become problematic if the decimal places are very long, as it requires multiplying by increasingly larger numbers.

728x90