Overview
simple_fraction provides exact rational arithmetic for Eiffel using fractions (numerator/denominator). Perfect for recipes, measurements, probabilities, and any calculation where precision matters.
The Problem with Decimals
Neither floating-point nor decimal can represent 1/3 exactly:
-- Every decimal representation of 1/3 is approximate
1.0 / 3.0 -- 0.33333333... (truncated somewhere)
This means 1/3 + 1/3 + 1/3 may not equal exactly 1!
The Solution
local
third, total: SIMPLE_FRACTION
do
create third.make (1, 3)
total := third + third + third
print (total.out) -- "1" (exactly 3/3 = 1)
end
Quick Start
Installation
- Set the environment variable:
export SIMPLE_EIFFEL=/d/prod - Add to your ECF file:
<library name="simple_fraction" location="$SIMPLE_EIFFEL/simple_fraction/simple_fraction.ecf"/>
Basic Usage
class
RECIPE_SCALER
feature -- Scaling
triple_recipe (ingredient: STRING): STRING
-- Triple a fractional ingredient amount
local
amount, tripled: SIMPLE_FRACTION
do
create amount.make_from_string (ingredient)
tripled := amount.scale (3)
Result := tripled.to_mixed_string
end
end
-- Usage:
scaler.triple_recipe ("2/3") -- Returns: "2"
scaler.triple_recipe ("1/4") -- Returns: "3/4"
scaler.triple_recipe ("1 1/2") -- Returns: "4 1/2"
Key Features
Exact Arithmetic
1/3 + 1/3 + 1/3 = 1 exactly. No rounding errors, no approximation.
Auto-Reduction
Fractions automatically reduce to lowest terms. 4/8 becomes 1/2.
Mixed Numbers
Full support for mixed numbers like 2 3/4. Create, display, extract parts.
Smart Parsing
Parse "3/4", "2 3/4", "0.5", or "5" - all work automatically.
Immutable Operations
All arithmetic returns new values. Thread-safe, predictable.
Design by Contract
Full preconditions, postconditions, and invariants throughout.
simple_fraction vs simple_decimal
| Feature | simple_fraction | simple_decimal |
|---|---|---|
| Best for | Ratios, recipes, probabilities | Money, financial, prices |
| 1/3 | Exact | Approximate |
| 0.1 | 1/10 (exact) | Exact |
| Output | "2 3/4" | "$19.99" |
Documentation
- User Guide - Complete tutorial with examples
- API Reference - Full feature documentation
- Architecture - Internal design and rationale
- Cookbook - Real-world recipes and patterns