🎯 Máy tính có lưu chính xác không?
🎯 Exact or Approximate?
Máy tính lưu số thực bằng hệ 2 với số bit hữu hạn. Có số được lưu chính xác (Exact), có số chỉ lưu được gần đúng (Approximate). Trả lời thật nhanh, rồi thử tự tìm ra quy luật.
Computers store real numbers in base 2 with a finite number of bits. Some numbers are stored exactly, others only approximately. Answer fast, then try to discover the rule yourself.
Gợi ý: nhớ lại game Bit Fishing. Con cá nào câu hết được?
Hint: remember Bit Fishing. Which fish could you catch completely?
Máy tính lưu số này…
🔎 Bạn đã thấy quy luật chưa?
Số thập phân như thế nào thì máy tính lưu chính xác được?
Which decimal numbers can a computer store exactly?
🧪 Hậu quả: 0.1 + 0.2 = ?
0.1 và 0.2 đều là loại gần đúng. Cộng hai số đã bị làm tròn thì kết quả ra sao? Bấm để máy tính của bạn tự tính thật (JavaScript dùng số thực 64-bit IEEE 754, giống Python).
0.1 and 0.2 are both approximate. What happens when you add two rounded numbers? Press the button and let your own computer do the real calculation (JavaScript uses 64-bit IEEE 754 floats, just like Python).
Vì thật ra máy tính không lưu 0.1. Nó lưu số nhị phân gần nhất:
Because the computer does not actually store 0.1. It stores the nearest binary number:
Hai sai số nhỏ cộng dồn lại, nên kết quả lệch khỏi số gần 0.3 nhất mà máy biểu diễn được.
The two tiny errors add up, so the result misses the closest representable number to 0.3.
==. Hãy dùng math.isclose(a, b) hoặc np.isclose(a, b). Tính tiền thì dùng decimal.Decimal hoặc lưu theo đơn vị nhỏ nhất (đồng, cent) bằng số nguyên.
==. Use math.isclose(a, b) or np.isclose(a, b). For money, use decimal.Decimal or store integers in the smallest unit (cents).
🔬 Thử số của bạn
Gõ một số thập phân để xem máy tính thực sự lưu giá trị gì.