搜尋此網誌

2026年3月23日星期一

Numbers in Python

int('100', 2)

means: convert the string '100' into an integer, interpreting it as a binary number.

A floating point error usually refers to the small inaccuracies that occur when computers represent and calculate with decimal numbers.

from decimal import Decimal, getcontext

The decimal module in Python is designed to avoid the floating point errors we just talked about. By using Decimal objects, you can represent numbers exactly as decimal fractions, and you can even control the precision of calculations with getcontext.

getcontext().prec = 4

round(0.1 + 0.2, 1)  # 0.3

Microsoft Copilot

沒有留言:

發佈留言