Commutative Swap
import mathy_core.rules.commutative_swap
Commutative Property
of numbers says that we can re-order two addition
or multiplication
terms so that one occurs before the other in the expression without changing the value of the expression. The formulation of this property is the same for addition and multiplication:
- Addition
a + b = b + a
- Multiplication
a * b = b * a
The commutative property is used for re-arranging the order of parts of an expression and is, as such, very important for working with mathematical expressions.
Transformations¶
Given a common parent node, this rule switches the order of the children of that node. It can only be applied to addition or multiplication nodes.
Addition¶
a + b = b + a
+ +
/ \ / \
/ \ -> / \
/ \ / \
a b b a
Multiplication¶
a * b = b * a
* *
/ \ / \
/ \ -> / \
/ \ / \
a b b a
Examples¶
Info
All the examples shown below are drawn from the mathy test suite that verifies the expected input/output combinations for rule transformations.
Input | Output | Valid |
---|---|---|
2x = 6x - 8 | 6x - 8 = 2x | ✔ |
2x + 1y^3 + 7j + -2q + 93m + 6x | 2x + 1y^3 + 7j + -2q + 6x + 93m | ✔ |
2x + 1y^3 + 7j + -2q + 6x + 93m | 2x + 1y^3 + 7j + 6x + -2q + 93m | ✔ |
2x + 1y^3 + 7j + 6x + -2q + 93m | 2x + 1y^3 + 6x + 7j + -2q + 93m | ✔ |
2x + 1y^3 + 6x + 7j + -2q + 93m | 2x + 6x + 1y^3 + 7j + -2q + 93m | ✔ |
12x * 10y | (x * 12) * 10y | ✔ |
2530z + 1m + 3.5x + 2z + 8.9c | 2530z + 3.5x + 1m + 2z + 8.9c | ✔ |
(5 + 12) * a | a * (5 + 12) | ✔ |
2b^4 * 3x | (b^4 * 2) * 3x | ✔ |
4 + 17 | 17 + 4 | ✔ |
4x | x * 4 | ✔ |
2^4 * 8 | 8 * 2^4 | ✔ |
(7 + x) + 2 | x + 7 + 2 | ✔ |
12x + 10y | 10y + 12x | ✔ |
8y^4 | --- | --- |
4x | --- | --- |
4 / 3 | --- | --- |
7 / x | --- | --- |
API¶
CommutativeSwapRule¶
CommutativeSwapRule(self, preferred: bool = True)
a + b = b + a
+ +
/ \ / \
/ \ -> / \
/ \ / \
a b b a
For Multiplication: a * b = b * a
* *
/ \ / \
/ \ -> / \
/ \ / \
a b b a