Think symbolicallyLesson 02 of 48 · 7 min
Keep numbers exact
Choose exact rational inputs before Python rounds a calculation.
Maths refresher: Fractions as numbers
A fraction means a divided by a nonzero b. Equivalent fractions represent the same number.
Three exact thirds make one. Writing 0.333 three times instead gives 0.999; extra printed digits do not restore the discarded information.
A rational number is an exact ratio of integers. In ordinary Python, dividing two integers with / produces a floating-point approximation. If that division happens before SymPy receives the value, the exact fraction has already been replaced.
Use Rational(1,3) or S(1)/3 to construct an exact third. SymPy then carries the fraction through algebra without rounding. A Float can be useful for approximate measurements, but it represents a different kind of input from an exact rational.
Read the exact input and the nearby value stored after Python division. Compare the stored fraction with the intended fraction by subtracting them. Choose exactness from the provenance of the input: a mathematical third can be exact; a measured decimal normally has its own uncertainty.
Does passing the already calculated Python value 1/3 to SymPy recover an exact third?
Write a prediction (optional)
Exact fraction and floating-point approximation
Select Run Python with the code unchanged.
Your saved draft is open. To use the published code, select Restore example in Tools. Use Recover draft to bring back your code.
Tools
About Python
Python and the course packages can load while you read. Each run starts with fresh user variables; imported modules stay loaded. Stop replaces the worker. Runtime details ↗
Ctrl+Enter or ⌘+Enter runs Python.
Execution error
Technical error details
Your result
Python text output
Compare with the worked example
Executed from the published Python during the site build. Your own run appears above. Build environment ↗
Worked text output
Exact input: 1/3 Approximate Python input: 0.333333333333333 Exact sum: 1 Stored float as a fraction: 6004799503160661/18014398509481984 Stored fraction minus exact: -1/54043195528445952 Exact decimal on request: 0.3333333333333333333333333
Read the starter result
Compare Exact input with Approximate Python input. The latter represents a nearby binary fraction. Stored fraction minus exact exposes a difference that may disappear at ordinary display precision.
Edit and compare
Replace sp.Rational(1,3) with sp.Rational("0.1") and sp.sympify(1/3) with sp.Float(0.1,30). Select Run Python. Compare Exact input, Approximate Python input and Stored fraction minus exact. What information was already lost before SymPy received the Python float?
Scope. Exact rational arithmetic does not make uncertain real-world observations exact.
Try a fresh case
Which input best represents an exact mathematical two sevenths?
Need a hint?
Hint 1
Look for the point where division is first evaluated.
Hint 2
Pass the numerator and denominator separately.