Sub topic 17
Checking Your Work with Python
This chapter assumes you already know the order of operations, fractions, integer exponents, and the difference between -3 ** 2 and (-3) ** 2. Python can check arithmetic, but it does not replace the reasoning used to decide how an expression is grouped.
Translating mathematics into Python
Use these operators:
| Mathematical operation | Python notation |
|---|---|
| Addition | `+` |
| Subtraction | `-` |
| Multiplication | `*` |
| Division | `/` |
| Exponentiation | `**` |
Python follows the usual precedence rules. Parentheses are evaluated first, then exponents, then multiplication and division from left to right, and finally addition and subtraction from left to right.
print(2 + 3 * 4 ** 2)
print((2 + 3) * 4 ** 2)
print(24 / 4 * 3)
print(24 / (4 * 3))The results are 50, 80, 18.0, and 2.0. The decimal point appears because / produces a floating-point number, which is Python's approximate representation of a real number.
Checking fractions exactly
Floating-point numbers can contain small rounding errors. For exact fraction arithmetic, use Fraction from Python's fractions module.
from fractions import Fraction
result = Fraction(1, 2) + Fraction(3, 4) * Fraction(2, 3) ** 2
print(result)
print(float(result))The exact result is 5/6. The second line displays an approximation, about 0.8333333333333334.
Build fractions with Fraction(numerator, denominator). Do not write Fraction(1 / 3) when you need exactness, because Python evaluates 1 / 3 as a floating-point approximation before Fraction receives it.
Checking the cases that cause errors
Python also helps test grouping and signs.
print(-3 ** 2)
print((-3) ** 2)
print(2 ** 3 ** 2)
print((2 ** 3) ** 2)
from fractions import Fraction
print(Fraction(2, 3) ** -2)The outputs are -9, 9, 512, 64, and 9/4. These results show that Python treats exponentiation as higher precedence than a leading minus sign and groups a stacked exponent from the top down.
Use a written solution to explain each step. Then use Python to compare the final result. If the results disagree, inspect the translation first. A missing * or a missing pair of parentheses often changes the expression.
A reliable checking process
When the hand result is a fraction, compare it with a Fraction result rather than a decimal. When the expression contains a fraction bar, put parentheses around both the numerator and denominator.
Exercise
Evaluate 1/2 + (3/4)(2/3)^2 by hand, then write Python code that checks the exact result.
Show answer
The result is 5/6. Use from fractions import Fraction and calculate Fraction(1, 2) + Fraction(3, 4) * Fraction(2, 3) ** 2.