fractions Keep Ratios Exact Without Drift

Keep ratios exact with Fraction: binary floats fail 0.1 plus 0.2 checks, fractions add and scale without drift, and results auto-reduce to lowest terms.

PythonData Integrity

Code

pythonsnippet
16 lines
from fractions import Fraction

# float 是二进制近似:0.1 + 0.2 != 0.3;Fraction 是精确有理数
print("float :", 0.1 + 0.2 == 0.3)
print("exact :", Fraction(1, 10) + Fraction(2, 10) == Fraction(3, 10))

# 配方缩放:1/3 杯翻倍再翻倍,仍是精确分数
cup = Fraction(1, 3)
print("scaled:", cup * 2 + cup * 2, "=", float(cup * 4))

# 分数自动约分到最简形式
print("simplified:", Fraction(8, 12), Fraction(-6, 16))

# 混合运算:分子分母保持 int,不会掉进 float 陷阱
total = Fraction(2, 5) + Fraction(1, 5)
print("sum:", total, "| as float:", float(total), "| pct:", float(total) * 100)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

float : False
exact : True
scaled: 4/3 = 1.3333333333333333
simplified: 2/3 -3/8
sum: 3/5 | as float: 0.6 | pct: 60.0

How the snippet works

From fractions it pulls Fraction — the imports name exactly which library surface the snippet touches.

The file’s state is a handful of top-level bindings: cup, total.

Points of care

  • Dependency check: fractions — not built-in, must be present in the project.

Using it

Running the file prints labeled results such as float :, exact :, scaled: — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `cup`, `total`.