(x: Expression)
| 63 | function simplifyAbsCore(x: Expression): RuleStep | undefined { |
| 64 | if (!isFunction(x, 'Abs')) return undefined; |
| 65 | |
| 66 | const op = x.op1; |
| 67 | if (!op) return undefined; |
| 68 | |
| 69 | const ce = x.engine; |
| 70 | |
| 71 | // |x| -> x when x is non-negative |
| 72 | if (op.isNonNegative === true) return { value: op, because: '|x| -> x' }; |
| 73 | |
| 74 | // |x| -> -x when x is non-positive (includes x < 0 and x = 0) |
| 75 | // Note: -0 = 0, so this is mathematically correct |
| 76 | if (op.isNonPositive === true) |
| 77 | return { value: op.neg(), because: '|x| -> -x' }; |
| 78 | |
| 79 | // |z| -> exact modulus when z is a constant complex expression whose |
| 80 | // magnitude reduces to a real number (|3+4i| -> 5, |1+i| -> √2, the Kahan |
| 81 | // value |3 - √7 + i√(6√7 - 15)| -> 1) is the constant folding of |
| 82 | // `simplify()` itself (`foldedConstant()` in `boxed-expression/simplify.ts`), |
| 83 | // which runs on this node when no rule rewrites it: the evaluate() handler |
| 84 | // (arithmetic.ts, evaluateAbs) computes the exact √(a²+b²) split and gives |
| 85 | // a number only when it genuinely folds. The fold is value-blind (|w| with |
| 86 | // `w := 5` stays |w|) and keeps an `Annotated` operand, which an |
| 87 | // evaluation here dropped. |
| 88 | |
| 89 | const opOperator = op.operator; |
| 90 | |
| 91 | // |-x| -> |x| |
| 92 | if (opOperator === 'Negate' && isFunction(op)) { |
| 93 | return { value: ce._fn('Abs', [op.op1]), because: '|-x| -> |x|' }; |
| 94 | } |
| 95 | |
| 96 | // |x * y| patterns |
| 97 | if (opOperator === 'Multiply' && isFunction(op)) { |
| 98 | const ops = op.ops; |
| 99 | |
| 100 | // Find if any factor has known sign |
| 101 | for (let i = 0; i < ops.length; i++) { |
| 102 | const factor = ops[i]; |
| 103 | |
| 104 | if (factor.isNonNegative === true) { |
| 105 | // |x * y| -> x * |y| when x is non-negative |
| 106 | const otherFactors = ops.filter((_, idx) => idx !== i); |
| 107 | const remaining = |
| 108 | otherFactors.length === 1 |
| 109 | ? otherFactors[0] |
| 110 | : ce._fn('Multiply', otherFactors); |
| 111 | return { |
| 112 | value: factor.mul(ce._fn('Abs', [remaining])), |
| 113 | because: '|xy| -> x|y| when x >= 0', |
| 114 | }; |
| 115 | } |
| 116 | |
| 117 | if (factor.isNonPositive === true) { |
| 118 | // |x * y| -> (-x) * |y| when x is non-positive |
| 119 | const otherFactors = ops.filter((_, idx) => idx !== i); |
| 120 | const remaining = |
| 121 | otherFactors.length === 1 |
| 122 | ? otherFactors[0] |
no test coverage detected