diff --git a/docs/js/demo.js b/docs/js/demo.js index 475d47a..292d322 100644 --- a/docs/js/demo.js +++ b/docs/js/demo.js @@ -925,11 +925,11 @@ class LatexToAst { result = Infinity; this.advance(); } else if (this.token.token_type === "deg") { - const degree = 355 / (180 * 113); + const degree = Math.PI / 180; result = ["*", degree]; this.advance(); } else if (this.token.token_type === "grad") { - const gradian = 355 / (200 * 113); + const gradian = Math.PI / 200; result = ["*", gradian]; this.advance(); } else if (this.token.token_type === "UNIT") { @@ -1723,7 +1723,9 @@ function contains$1(array, item) { return array.indexOf(item) !== -1; } function validateOption(options, name, values) { - if (options[name] !== undefined && !contains$1(values, options[name])) ; + if (options[name] !== undefined && !contains$1(values, options[name])) { + console.warn('Warning: Unknown value "' + options[name] + '" for configuration option "' + name + '". ' + 'Available options: ' + values.map(value => JSON.stringify(value)).join(', ') + '.'); + } } var typedFunction = createCommonjsModule(function (module, exports) { @@ -33354,6 +33356,9 @@ var createEigs = factory(name$Q, dependencies$Q, _ref => { } } } + if (hasBig && hasComplex) { + console.warn('Complex BigNumbers not supported, this operation will lose precission.'); + } if (hasComplex) { for (var _i = 0; _i < N; _i++) { for (var _j = 0; _j < N; _j++) { @@ -35759,6 +35764,7 @@ var createUtil = factory(name$p, dependencies$p, _ref => { try { return new OperatorNode(node.op, node.fn, args, node.implicit); } catch (err) { + console.error(err); return []; } }; @@ -39170,6 +39176,7 @@ function create(factories, config) { return firstProperty(math); } if (!isLegacyFactory(factory)) { + console.warn('Factory object with properties `type`, `name`, and `factory` expected', factory); throw new Error('Factory object with properties `type`, `name`, and `factory` expected'); } var index = legacyFactories.indexOf(factory); @@ -39745,6 +39752,7 @@ const sort = (node) => { function _optionalChain$2(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }const { simplify: simplify$2 } = mathjs; const m$4 = mathjs; +const numeric$1 = create(all); let simplifyRules = [ { l: "-((n1)*(n2))", r: "(n1)*(n2)" }, { l: "(n1-n2)/n3", r: "n1/n3-n2/n3" }, @@ -39784,36 +39792,193 @@ const hasSymbolicExponent = (node) => { if ( n.isOperatorNode && n.op === "^" && - !_optionalChain$2([n, 'access', _ => _.args, 'access', _2 => _2[1], 'optionalAccess', _3 => _3.isConstantNode]) + !_optionalChain$2([n, 'access', _2 => _2.args, 'access', _3 => _3[1], 'optionalAccess', _4 => _4.isConstantNode]) ) { found = true; } }); return found; }; +const seededRandom = (seed) => () => { + seed = (seed + 0x6d2b79f5) | 0; + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; +}; +const getSamplePoints = (variables, count = 12) => { + const random = seededRandom(443); + return Array.from({ length: count }, () => + variables.reduce((acc, v) => { + const size = 0.5 + 4 * random(); + acc[v] = random() < 0.5 ? -size : size; + return acc; + }, {} ) + ); +}; +const evaluateAtPoints = (expr, points) => { + let compiled; + try { + compiled = numeric$1.compile(expr.toString()); + } catch (e2) { + return points.map(() => NaN); + } + return points.map((scope) => { + try { + const result = compiled.evaluate({ ...scope }); + return typeof result === "number" ? result : NaN; + } catch (e3) { + return NaN; + } + }); +}; +const areClose = (a, b, tolerance) => + Math.abs(a - b) <= tolerance * Math.max(1, Math.abs(a), Math.abs(b)); const areNumericallyEquivalent = ( exprA, exprB, variables, tolerance = 1e-10 ) => { - const compiledA = m$4.compile(exprA.toString()); - const compiledB = m$4.compile(exprB.toString()); - const testValues = [1, 2, 3, 4, 5]; - return testValues.every((val) => { - const scope = variables.reduce((acc, v) => { - acc[v] = val; - return acc; - }, {} ); - try { - const resultA = compiledA.evaluate(scope); - const resultB = compiledB.evaluate(scope); - return Math.abs(resultA - resultB) < tolerance; - } catch (e2) { + const points = getSamplePoints(variables); + const valuesA = evaluateAtPoints(exprA, points); + const valuesB = evaluateAtPoints(exprB, points); + const compared = valuesA.filter( + (a, i) => Number.isFinite(a) && Number.isFinite(valuesB[i]) + ); + return ( + compared.length >= 3 && + valuesA.every( + (a, i) => + !Number.isFinite(a) || + !Number.isFinite(valuesB[i]) || + areClose(a, valuesB[i], tolerance) + ) + ); +}; +const getVariableFactors = (variables, maxPower) => + variables.reduce( + (factors, v) => + factors.reduce( + (acc, factor) => + acc.concat( + Array.from({ length: 2 * maxPower + 1 }, (_, i) => ({ + ...factor, + [v]: i - maxPower, + })) + ), + [] + ), + [{}] + ); +const haveProportionalValues = ( + firstExpression, + secondExpression, + variables, + { + allowVariableFactor = false, + positiveOnly = false, + } = {} +) => { + const tolerance = 1e-9; + const points = getSamplePoints(variables); + const firstValues = evaluateAtPoints(firstExpression, points); + const secondValues = evaluateAtPoints(secondExpression, points); + const ratios = []; + for (let i = 0; i < points.length; i++) { + const f = firstValues[i]; + const g = secondValues[i]; + if (!Number.isFinite(f) || !Number.isFinite(g)) { + continue; + } + const fIsZero = Math.abs(f) < tolerance; + const gIsZero = Math.abs(g) < tolerance; + if (fIsZero && gIsZero) { + continue; + } + if (fIsZero || gIsZero) { return false; } + ratios.push({ point: points[i], ratio: f / g }); + } + if (ratios.length < 3) { + return false; + } + const factors = allowVariableFactor + ? getVariableFactors(variables, 2).filter( + (factor) => + !positiveOnly || Object.values(factor).every((power) => power % 2 === 0) + ) + : [{} ]; + return factors.some((factor) => { + const scaled = ratios.map(({ point, ratio }) => + Object.keys(factor).reduce( + (acc, v) => acc / Math.pow(point[v], factor[v]), + ratio + ) + ); + return ( + (!positiveOnly || scaled[0] > 0) && + scaled.every((r) => areClose(r, scaled[0], tolerance)) + ); }); }; +const MAX_NUMERATOR_POWER = 4; +const MAX_NUMERATOR_NODES = 60; +const isTooLargeToRationalize = (expr) => { + let nodes = 0; + let tooLarge = false; + expr.traverse((n) => { + nodes++; + tooLarge = + tooLarge || + (n.isOperatorNode && + n.op === "^" && + _optionalChain$2([n, 'access', _5 => _5.args, 'access', _6 => _6[1], 'optionalAccess', _7 => _7.isConstantNode]) && + Math.abs(Number(n.args[1].value)) > MAX_NUMERATOR_POWER); + }); + return tooLarge || nodes > MAX_NUMERATOR_NODES; +}; +const getNumerator = (expr) => { + if (isTooLargeToRationalize(expr)) { + return undefined; + } + try { + const { numerator, denominator } = numeric$1.rationalize( + expr.toString(), + {}, + true + ); + return denominator ? numerator : undefined; + } catch (e4) { + return undefined; + } +}; +const areEquationsNumericallyEquivalent = ( + firstExpression, + secondExpression, + variables, + options = {} +) => { + if ( + haveProportionalValues(firstExpression, secondExpression, variables, options) + ) { + return true; + } + if (options.positiveOnly) { + return false; + } + const firstNumerator = getNumerator(firstExpression); + const secondNumerator = getNumerator(secondExpression); + return ( + (firstNumerator !== undefined || secondNumerator !== undefined) && + haveProportionalValues( + firstNumerator || firstExpression, + secondNumerator || secondExpression, + variables, + options + ) + ); +}; const transformEqualityInExpression = (equality) => simplify$1(new m$4.OperatorNode("-", "subtract", equality.args)); const getVariables = (equation) => { @@ -39821,7 +39986,7 @@ const getVariables = (equation) => { equation.traverse(function (node, path, parent) { if ( node.isSymbolNode && - _optionalChain$2([node, 'optionalAccess', _4 => _4.name, 'access', _5 => _5.length]) === 1 && + _optionalChain$2([node, 'optionalAccess', _8 => _8.name, 'access', _9 => _9.length]) === 1 && !variableNames.includes(node.name) ) { variableNames.push(node.name); @@ -39851,13 +40016,6 @@ const getCoefficients = (equation, isInequality) => { } return [1, 0]; }; -const setXToOne = (equation, variableName) => - equation.transform(function (node, path, parent) { - if (node.isSymbolNode && node.name === variableName) { - return new m$4.ConstantNode(1); - } - return node; - }); const solveQuadraticEquation = (coefficients) => { const [c, b, a] = coefficients; const discriminant = b * b - 4 * a * c; @@ -39867,14 +40025,14 @@ const solveQuadraticEquation = (coefficients) => { addDiscriminant = m$4.compile( m$4.fraction(-b + m$4.sqrt(discriminant)) / (2 * a) ); - } catch (e3) { + } catch (e5) { addDiscriminant = m$4.compile("(-b+sqrt(discriminant))/(2*a)"); } try { subtractDiscriminant = m$4.compile( m$4.fraction(-b - m$4.sqrt(discriminant)) / (2 * a) ); - } catch (e4) { + } catch (e6) { subtractDiscriminant = m$4.compile("(-b-sqrt(discriminant))/(2*a)"); } let firstRoot = addDiscriminant.evaluate({ @@ -40044,18 +40202,25 @@ const compareEquations = ( equivalence = solutionForFirstEquation === solutionForSecondEquation && solutionForFirstEquation !== undefined; + if ( + !isInequality && + (solutionForFirstEquation === undefined || + solutionForSecondEquation === undefined) + ) { + return areEquationsNumericallyEquivalent( + firstExpression, + secondExpression, + firstEquationVariablesName + ); + } } if (firstEquationVariablesName.length === 2) { - let x = firstEquationVariablesName[0]; - let expraNoX = setXToOne(firstExpression, x); - firstEquationCoefficients = getCoefficients(expraNoX, isInequality); - let exprbNoX = setXToOne(secondExpression, x); - secondEquationCoefficients = getCoefficients(exprbNoX, isInequality); - let yFromFirstExpression = solveLinearEquation(firstEquationCoefficients); - let yFromSecondExpression = solveLinearEquation( - secondEquationCoefficients + return areEquationsNumericallyEquivalent( + firstExpression, + secondExpression, + firstEquationVariablesName, + { allowVariableFactor: true, positiveOnly: isInequality } ); - equivalence = yFromFirstExpression === yFromSecondExpression; } if (equivalence && isInequality) { return !( @@ -40151,8 +40316,10 @@ const compareCompoundInequations = ( function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }const m$1 = mathjs; const log$1 = logger("mv:symbolic"); -const positiveInfinity = 1.497258191621251e6; -const negativeInfinity = -1.497258191621251e6; +const ANGLE_TOLERANCE = 1e-9; +const numeric = create(all); +const RELATIVE_EPSILON = 1e-13; +const ABSOLUTE_EPSILON = 1e-14; const { simplify: ms$1, rationalize } = mathjs; const SIMPLIFY_RULES = [ { l: "n1^(1/n2)", r: "nthRoot(n1, n2)" }, @@ -40195,8 +40362,81 @@ const simplify$1 = (v) => { const rules = SIMPLIFY_RULES.concat((ms$1 ).rules); return ms$1(v, rules); }; +const hasSymbol = (node, matches) => { + let found = false; + node.traverse((n, path) => { + found = found || (n.isSymbolNode && path !== "fn" && matches(n.name)); + }); + return found; +}; +const evaluateNumber = (node) => { + if (hasSymbol(node, (name) => name !== "pi" && name !== "Infinity")) { + return undefined; + } + try { + const value = numeric.evaluate(node.toString()); + return typeof value === "number" ? value : undefined; + } catch (e) { + return undefined; + } +}; +const quarterTurns = (angle) => { + const value = evaluateNumber(angle); + if (value === undefined || !isFinite(value)) { + return undefined; + } + const turns = value / (Math.PI / 2); + const k = Math.round(turns); + return Math.abs(turns - k) <= ANGLE_TOLERANCE * Math.max(1, Math.abs(k)) + ? k + : undefined; +}; +const snapTrigonometricValues = (node) => { + let changed = false; + const r = node.transform((n) => { + if (!n.isFunctionNode || _optionalChain([n, 'access', _ => _.args, 'optionalAccess', _2 => _2.length]) !== 1) { + return n; + } + const k = quarterTurns(n.args[0]); + if (k === undefined) { + return n; + } + const odd = Math.abs(k) % 2 === 1; + let snapped = n; + switch (n.fn.name) { + case "sin": + snapped = odd ? n : new m$1.ConstantNode(0); + break; + case "cos": + snapped = odd ? new m$1.ConstantNode(0) : n; + break; + case "tan": + snapped = odd ? new m$1.SymbolNode("Infinity") : new m$1.ConstantNode(0); + break; + case "cot": + snapped = odd ? new m$1.ConstantNode(0) : new m$1.SymbolNode("Infinity"); + break; + case "sec": + snapped = odd ? new m$1.SymbolNode("Infinity") : n; + break; + case "csc": + snapped = odd ? n : new m$1.SymbolNode("Infinity"); + break; + } + changed = changed || snapped !== n; + return snapped; + }); + return { r: changed ? r : node, changed }; +}; const normalize = (a) => { - let r = a; + const snapped = snapTrigonometricValues(a); + let r = snapped.r; + const snappedValue = snapped.changed ? evaluateNumber(r) : undefined; + const valueWithSnappedTrigonometry = + snappedValue !== undefined && + (!isFinite(snappedValue) || hasSymbol(r, (name) => name === "Infinity")) + ? snappedValue + : undefined; let onlyConstant = true; let containsFunctionNode = false; let containsArrayNode = false; @@ -40256,56 +40496,78 @@ const normalize = (a) => { } catch (e) {} } log$1("[normalize] input: ", a.toString(), "output: ", r.toString()); - if ( - r.toString() === "Infinity" || - +r.toString() >= positiveInfinity || - +r.toString() <= negativeInfinity - ) { + if (valueWithSnappedTrigonometry !== undefined) { + r = isNaN(valueWithSnappedTrigonometry) + ? new m$1.SymbolNode("NaN") + : isFinite(valueWithSnappedTrigonometry) + ? new m$1.ConstantNode(valueWithSnappedTrigonometry) + : new m$1.SymbolNode("Infinity"); + } + if (r.toString() === "Infinity") { r = new m$1.SymbolNode("Infinity"); } - if (r.value) { - r.value = new m$1.Fraction(Math.round(r.value * 10000) / 10000); - } else if (r.fn === "unaryMinus") { - r.args[0].value = new m$1.Fraction( - Math.round(r.args[0].value * 10000) / 10000 - ); - r = simplify$1(r); - } return r; }; +const constantValue = (node) => { + if (node.filter((n) => n.isSymbolNode).length > 0) { + return undefined; + } + try { + const result = node.evaluate(); + if (typeof result === "boolean") { + return undefined; + } + const value = +result; + return Number.isFinite(value) ? value : undefined; + } catch (e) { + return undefined; + } +}; +const areNearlyEqual = (a, b) => + Math.abs(a - b) < + ABSOLUTE_EPSILON + RELATIVE_EPSILON * Math.max(Math.abs(a), Math.abs(b)); +const isIndeterminate = (node) => _optionalChain([node, 'optionalAccess', _3 => _3.isSymbolNode]) && node.name === "NaN"; const isMathEqual$1 = (a, b) => { let as; let bs; - if (_optionalChain([a, 'optionalAccess', _ => _.isUnit]) && _optionalChain([b, 'optionalAccess', _2 => _2.isUnit])) { + if (_optionalChain([a, 'optionalAccess', _4 => _4.isUnit]) && _optionalChain([b, 'optionalAccess', _5 => _5.isUnit])) { try { return m$1.equal(a, b); } catch (e) { log$1( "[isMathEqual] Error comparing units:", - _optionalChain([a, 'optionalAccess', _3 => _3.toString, 'optionalCall', _4 => _4()]), - _optionalChain([b, 'optionalAccess', _5 => _5.toString, 'optionalCall', _6 => _6()]), + _optionalChain([a, 'optionalAccess', _6 => _6.toString, 'optionalCall', _7 => _7()]), + _optionalChain([b, 'optionalAccess', _8 => _8.toString, 'optionalCall', _9 => _9()]), e ); return false; } } - if (_optionalChain([a, 'optionalAccess', _7 => _7.isUnit]) || _optionalChain([b, 'optionalAccess', _8 => _8.isUnit])) { + if (_optionalChain([a, 'optionalAccess', _10 => _10.isUnit]) || _optionalChain([b, 'optionalAccess', _11 => _11.isUnit])) { log$1( "[isMathEqual] Mismatched unit comparison:", - _optionalChain([a, 'optionalAccess', _9 => _9.toString, 'optionalCall', _10 => _10()]), - _optionalChain([b, 'optionalAccess', _11 => _11.toString, 'optionalCall', _12 => _12()]) + _optionalChain([a, 'optionalAccess', _12 => _12.toString, 'optionalCall', _13 => _13()]), + _optionalChain([b, 'optionalAccess', _14 => _14.toString, 'optionalCall', _15 => _15()]) ); return false; } as = a.conditionals ? normalize(a) : sort(normalize(a)); bs = b.conditionals ? normalize(b) : sort(normalize(b)); log$1("[isMathEqual]", as.toString(), "==?", bs.toString()); + if (isIndeterminate(as) || isIndeterminate(bs)) { + return false; + } const isSortingEnough = sort(a).equals(sort(b)); const isTexEnough = as.toTex().trim() === bs.toTex().trim(); let equality = isTexEnough || as.equals(bs) || isSortingEnough; if (equality) { return true; } + const aValue = constantValue(as); + const bValue = constantValue(bs); + if (aValue !== undefined && bValue !== undefined) { + return areNearlyEqual(aValue, bValue); + } if (as.fn === "equal" && bs.fn === "equal") { return compareEquations(as, bs, false); } @@ -40320,9 +40582,9 @@ const isMathEqual$1 = (a, b) => { return compareEquations(as, bs, true); } if ( - _optionalChain([as, 'optionalAccess', _13 => _13.conditionals, 'optionalAccess', _14 => _14.length]) === _optionalChain([bs, 'optionalAccess', _15 => _15.conditionals, 'optionalAccess', _16 => _16.length]) && - _optionalChain([as, 'optionalAccess', _17 => _17.conditionals, 'optionalAccess', _18 => _18.length]) === 2 && - _optionalChain([as, 'optionalAccess', _19 => _19.conditionals, 'optionalAccess', _20 => _20.toString, 'call', _21 => _21()]) === _optionalChain([bs, 'optionalAccess', _22 => _22.conditionals, 'optionalAccess', _23 => _23.toString, 'call', _24 => _24()]) + _optionalChain([as, 'optionalAccess', _16 => _16.conditionals, 'optionalAccess', _17 => _17.length]) === _optionalChain([bs, 'optionalAccess', _18 => _18.conditionals, 'optionalAccess', _19 => _19.length]) && + _optionalChain([as, 'optionalAccess', _20 => _20.conditionals, 'optionalAccess', _21 => _21.length]) === 2 && + _optionalChain([as, 'optionalAccess', _22 => _22.conditionals, 'optionalAccess', _23 => _23.toString, 'call', _24 => _24()]) === _optionalChain([bs, 'optionalAccess', _25 => _25.conditionals, 'optionalAccess', _26 => _26.toString, 'call', _27 => _27()]) ) { const params = [ "smaller", @@ -40613,6 +40875,7 @@ function setup(env) { return val; } function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; @@ -40626,7 +40889,12 @@ exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { + let warned = false; return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } }; })(); exports.colors = [ diff --git a/src/__tests__/utils.spec.ts b/src/__tests__/utils.spec.ts index 0c6c3eb..5c31829 100644 --- a/src/__tests__/utils.spec.ts +++ b/src/__tests__/utils.spec.ts @@ -5,11 +5,13 @@ import { simplify } from "../symbolic"; import { getVariables, getCoefficients, - setXToOne, solveLinearEquation, solveQuadraticEquation, expressionsCanBeCompared, transformEqualityInExpression, + getSamplePoints, + areNumericallyEquivalent, + areEquationsNumericallyEquivalent, } from "../symbolic/utils"; const lta = new LatexToAst(); @@ -137,26 +139,6 @@ describe("getCoefficients", () => { }); }); -describe("setXToOne", () => { - it.each` - expression | expressionNoX - ${"x+0"} | ${"1+0"} - ${"x +1"} | ${"1+1"} - ${"((x^2 + x) / x) - 1"} | ${"((1^2 + 1) / 1) - 1"} - ${"1+2"} | ${"1+2"} - ${"a +1+c"} | ${"a+1+c"} - ${"y^2+5x - 1"} | ${"y^2+5*1 - 1"} - ${"109h"} | ${"109h"} - ${"m+n+10"} | ${"m+n+10"} - `("$expression => $expressionNoX", ({ expression, expressionNoX }) => { - const equation = atm.convert(lta.convert(expression)); - const equationNoX = setXToOne(equation, "x"); - const result = atm.convert(lta.convert(expressionNoX)); - - expect(equationNoX.toTex()).toEqual(result.toTex()); - }); -}); - describe("solveLinearEquation", () => { it.each` coefficients | xValue @@ -250,3 +232,147 @@ describe("solveLinearEquation", () => { expect(result).toEqual(undefined); }); }); + +describe("getSamplePoints", () => { + it("gives each variable its own non-integer value, the same on every call", () => { + const points = getSamplePoints(["x", "y"]); + + points.forEach((point) => { + expect(point.x).not.toEqual(point.y); + expect(Number.isInteger(point.x)).toEqual(false); + expect(Number.isInteger(point.y)).toEqual(false); + }); + + expect(getSamplePoints(["x", "y"])).toEqual(points); + }); + + it("includes negative and positive values for each variable", () => { + const points = getSamplePoints(["x", "y"]); + + ["x", "y"].forEach((v) => { + expect(points.some((point) => point[v] < 0)).toEqual(true); + expect(points.some((point) => point[v] > 0)).toEqual(true); + }); + }); +}); + +describe("areNumericallyEquivalent", () => { + it('"x^2" and "y^2" are not equivalent', () => { + const a = atm.convert(lta.convert("x^2")); + const b = atm.convert(lta.convert("y^2")); + + expect(areNumericallyEquivalent(a, b, ["x", "y"])).toEqual(false); + }); + + it('"(x+y)^2" and "x^2+2xy+y^2" are equivalent', () => { + const a = atm.convert(lta.convert("(x+y)^2")); + const b = atm.convert(lta.convert("x^2+2xy+y^2")); + + expect(areNumericallyEquivalent(a, b, ["x", "y"])).toEqual(true); + }); +}); + +describe("areEquationsNumericallyEquivalent", () => { + const expression = (latex: string) => + transformEqualityInExpression(atm.convert(lta.convert(latex))); + + it('"x^2/16+y^2/9=1" and "9x^2+16y^2=144" are equivalent: one is a constant multiple of the other', () => { + const result = areEquationsNumericallyEquivalent( + expression("\\frac{x^2}{16}+\\frac{y^2}{9}=1"), + expression("9x^2+16y^2=144"), + ["x", "y"] + ); + + expect(result).toEqual(true); + }); + + it('"x^2/16+y^2/9=1" and "x^2/17+y^2/9=1" are not equivalent', () => { + const result = areEquationsNumericallyEquivalent( + expression("\\frac{x^2}{16}+\\frac{y^2}{9}=1"), + expression("\\frac{x^2}{17}+\\frac{y^2}{9}=1"), + ["x", "y"] + ); + + expect(result).toEqual(false); + }); + + it('"x+2y=7" and "x^2+2xy-7x=0" are equivalent only when a variable factor is allowed', () => { + const first = expression("x+2y=7"); + const second = expression("x^2+2xy-7x=0"); + + expect(areEquationsNumericallyEquivalent(first, second, ["x", "y"])).toEqual( + false + ); + expect( + areEquationsNumericallyEquivalent(first, second, ["x", "y"], { + allowVariableFactor: true, + }) + ).toEqual(true); + }); + + it('"(y-1)/(x-2)=3" and "y-1=3(x-2)" are equivalent: both sides were multiplied by the denominator', () => { + const result = areEquationsNumericallyEquivalent( + expression("\\frac{y-1}{x-2}=3"), + expression("y-1=3(x-2)"), + ["x", "y"] + ); + + expect(result).toEqual(true); + }); + + it('"y>2x+1" and "2y>4x+2" are the same inequality: one is a positive multiple of the other', () => { + const result = areEquationsNumericallyEquivalent( + expression("y>2x+1"), + expression("2y>4x+2"), + ["x", "y"], + { positiveOnly: true } + ); + + expect(result).toEqual(true); + }); + + it('"y>2x+1" and "-y>-2x-1" are different inequalities: the multiple is negative', () => { + const first = expression("y>2x+1"); + const second = expression("-y>-2x-1"); + + expect(areEquationsNumericallyEquivalent(first, second, ["x", "y"])).toEqual( + true + ); + expect( + areEquationsNumericallyEquivalent(first, second, ["x", "y"], { + positiveOnly: true, + }) + ).toEqual(false); + }); + + it('inequalities allow multiplying by an even power of a variable, but not an odd one', () => { + const options = { allowVariableFactor: true, positiveOnly: true }; + + expect( + areEquationsNumericallyEquivalent( + expression("y>x"), + expression("x^2y>x^3"), + ["x", "y"], + options + ) + ).toEqual(true); + expect( + areEquationsNumericallyEquivalent( + expression("y>x"), + expression("xy>x^2"), + ["x", "y"], + options + ) + ).toEqual(false); + }); + + it('"y=|x|" and "y=x" are not equivalent: they differ for negative x', () => { + const result = areEquationsNumericallyEquivalent( + expression("y=\\left|x\\right|"), + expression("y=x"), + ["x", "y"] + ); + + expect(result).toEqual(false); + }); +}); diff --git a/src/conversion/__tests__/latex-to-ast.spec.ts b/src/conversion/__tests__/latex-to-ast.spec.ts index 183e77e..00463b6 100644 --- a/src/conversion/__tests__/latex-to-ast.spec.ts +++ b/src/conversion/__tests__/latex-to-ast.spec.ts @@ -2,10 +2,10 @@ import { LatexToAst } from "../latex-to-ast"; // import { latexParser } from "latex-utensils"; // conversion of degrees in radians - angle configuration -const degree = 355 / (180 * 113); +const degree = Math.PI / 180; //conversion of gradians in radians - angle configuration -const gradian = 355 / (200 * 113); +const gradian = Math.PI / 200; const fixtures = [ //parentheses are stripped! diff --git a/src/conversion/latex-to-ast.ts b/src/conversion/latex-to-ast.ts index b9987d9..5bdaf2d 100644 --- a/src/conversion/latex-to-ast.ts +++ b/src/conversion/latex-to-ast.ts @@ -1168,7 +1168,7 @@ export class LatexToAst { this.advance(); } else if (this.token.token_type === "deg") { // conversion of degrees in radians - angle configuration - const degree = 355 / (180 * 113); + const degree = Math.PI / 180; // @ts-ignore result = ["*", degree]; @@ -1176,7 +1176,7 @@ export class LatexToAst { this.advance(); } else if (this.token.token_type === "grad") { //conversion of gradians in radians - angle configuration - const gradian = 355 / (200 * 113); + const gradian = Math.PI / 200; // @ts-ignore result = ["*", gradian]; diff --git a/src/fixtures/latex-equal/symbolic/PIE-1418.ts b/src/fixtures/latex-equal/symbolic/PIE-1418.ts new file mode 100644 index 0000000..268c727 --- /dev/null +++ b/src/fixtures/latex-equal/symbolic/PIE-1418.ts @@ -0,0 +1,146 @@ +// large numbers must be compared by value, only undefined trigonometric values count as infinity +// before PIE-1418 any number of 1,497,258 or more (or -1,497,258 or less) was treated as infinity +export default { + mode: "symbolic", + tests: [ + { + target: "2000000", + eq: ["2\\times10^6", "2000000.0", "\\frac{4000000}{2}"], + ne: ["3000000", "2000001", "1999999", "\\infty", "\\tan(90°)"], + }, + { + target: "-2000000", + eq: ["-2\\times10^6", "-\\frac{4000000}{2}"], + ne: ["-3000000", "2000000", "-\\infty"], + }, + { + // the old cutoff, values on both sides of it + target: "1497259", + ne: ["1497258", "1497260", "1600000", "\\infty"], + }, + { + target: "10^9", + eq: ["1000000000", "10^{9}"], + ne: ["10^{10}", "999999999"], + }, + { + label: "large value with a trigonometric function: $target", + target: "2000000\\sin(90°)", + eq: ["2000000"], + ne: ["3000000", "\\infty"], + }, + { + target: "\\infty", + eq: [ + "\\tan(90°)", + "-\\tan(90°)", + "2\\tan(90°)", + "\\tan(-90°)", + "\\tan(450°)", + "\\tan(3\\pi/2)", + "\\frac{1}{\\cos(90°)}", + "\\frac{1}{\\sin(180°)}", + ], + ne: ["2000000", "-\\infty", "\\tan(89°)", "\\tan(45°)"], + }, + { + label: "undefined trigonometric value in a sum: $target", + target: "3", + eq: ["\\frac{1}{\\tan(90°)}+3", "3+\\cot(90°)"], + ne: ["\\tan(90°)+3"], + }, + { + label: "angles that are only close to a multiple of 90° are not undefined: $target", + target: "\\infty", + eq: ["\\tan(810°)", "\\tan(4590°)", "\\tan(100\\grad)", "\\sqrt{\\tan(90°)}"], + ne: [ + "\\tan(1.5708)", + "\\tan(89.9999°)", + "\\tan(89.9995°)", + "\\tan(\\frac{\\pi}{2}+0.00001)", + "\\csc(3.1416)", + ], + }, + { + target: "\\sin(3.1416)\\cdot10^6", + ne: ["0", "\\infty"], + }, + { + label: "angles far from a multiple of 90° are not matched, however large: $target", + target: "\\infty", + ne: ["\\tan(9090.001°)", "\\tan(90089.99°)", "\\tan(1572.367)"], + }, + { + target: "0", + ne: ["\\tan(10000000)", "\\tan(3999999)"], + }, + { + label: "a replaced zero keeps exact fractions exact: $target", + target: "\\frac{1}{3}", + eq: ["\\sin(0)+\\frac{1}{3}", "\\frac{1+\\sin(0)}{3}"], + ne: ["\\sin(0)+0.3333"], + }, + { + target: "-\\frac{1}{3}", + eq: ["\\sin(0)-\\frac{1}{3}"], + }, + { + target: "\\frac{5}{6}", + eq: ["\\tan(0°)+\\frac{5}{6}"], + }, + { + label: "letters next to a replaced zero are variables, not constants: $target", + target: "\\phi", + eq: ["\\sin(0)+\\phi"], + ne: ["\\sin(0)+1.618"], + }, + { + target: "e", + eq: ["\\sin(0)+e"], + }, + { + label: "indeterminate results are not equal to each other: $target", + target: "\\tan(90°)-\\tan(90°)", + ne: ["\\tan(90°)-\\tan(90°)+7", "0\\cdot\\tan(90°)"], + }, + { + target: "\\frac{\\tan(90°)}{\\tan(90°)}", + ne: ["1", "\\frac{\\tan(90°)}{\\tan(90°)}+5"], + }, + { + label: "division by a zero of tan and cot: $target", + target: "\\infty", + eq: [ + "\\frac{1}{\\tan(180°)}", + "\\frac{1}{\\tan(\\pi)}", + "\\cot(180°)", + "\\frac{1}{\\cot(90°)}", + ], + }, + { + target: "0", + eq: ["\\tan(180°)", "\\cot(90°)", "\\cos(90°)\\cdot10^7"], + // indeterminate, not 0 + ne: ["\\tan(90°)-\\tan(90°)", "0\\cdot\\tan(90°)"], + }, + { + label: "division by zero has no sign: $target", + target: "-\\frac{1}{\\cos(90°)}", + eq: ["\\infty", "-\\sec(90°)", "\\frac{1}{\\cos(90°)}"], + ne: ["-\\infty"], + }, + { + target: "\\frac{2}{\\sin(180°)}", + eq: ["\\frac{-2}{\\sin(180°)}", "\\infty"], + }, + { + label: "undefined value next to a variable: $target", + target: "x=\\infty", + eq: ["x=\\tan(90°)"], + }, + { + target: "x+\\infty", + eq: ["x+\\tan(90°)"], + }, + ], +}; diff --git a/src/fixtures/latex-equal/symbolic/PIE-1419.ts b/src/fixtures/latex-equal/symbolic/PIE-1419.ts new file mode 100644 index 0000000..7a450ff --- /dev/null +++ b/src/fixtures/latex-equal/symbolic/PIE-1419.ts @@ -0,0 +1,81 @@ +// two-variable inequalities must describe the same region, not just agree at x = 1 +export default { + mode: "symbolic", + tests: [ + { + label: "$target", + target: "y>2x+1", + eq: [ + "y-2x>1", + "y-2x-1>0", + "2y>4x+2", + "2x+13x", + "y>x+2", + // same line, opposite side + "y<2x+1", + "y\\ge2x+1", + "-y>-2x-1", + ], + }, + { + label: "$target", + target: "3x-2y\\ge6", + eq: ["3x-6\\ge2y", "-3x+2y\\le-6", "6x-4y\\ge12", "2y\\le3x-6"], + ne: ["3x-2y\\ge5", "2x-3y\\ge6", "3x-2y\\le6", "3x+2y\\ge6"], + }, + { + // not linear in y, so the x = 1 check could not solve it + label: "$target", + target: "x^2+y^2\\le4", + eq: ["4\\ge x^2+y^2", "2x^2+2y^2\\le8", "x^2+y^2-4\\le0"], + ne: ["x^2+y^2\\le5", "x^2+2y^2\\le4", "x^2+y^2\\ge4"], + }, + { + label: "$target", + target: "y^2>x", + eq: ["2y^2>2x", "x0"], + ne: ["y^2>2x", "y^3>x", "y^2x", + eq: ["y-x>0", "2y>2x", "x1", + "\\frac{1}{y}<\\frac{1}{x}", + "y\\cdot y>x\\cdot y", + "(y-x)x>0", + ], + }, + { + label: "$target", + target: "xy>1", + ne: ["y>\\frac{1}{x}"], + }, + { + // both sides multiplied or divided by an even power of a variable, which can't reverse the sign + label: "$target", + target: "y>x^2", + eq: ["\\frac{y}{x^2}>1", "x^2y>x^4"], + ne: ["\\frac{y}{x}>x", "xy>x^3"], + }, + { + label: "$target", + target: "y>2x+1", + eq: ["x^2y>x^2(2x+1)"], + }, + { + // with the function in the target, the numeric check decides + label: "$target", + target: "y>\\left|x\\right|", + ne: ["y>x", "y>-x"], + }, + ], +}; diff --git a/src/fixtures/latex-equal/symbolic/PIE-443.ts b/src/fixtures/latex-equal/symbolic/PIE-443.ts new file mode 100644 index 0000000..27c8bfb --- /dev/null +++ b/src/fixtures/latex-equal/symbolic/PIE-443.ts @@ -0,0 +1,186 @@ +// two-variable equations with powers: changing a number or an exponent must make the answer incorrect +// targets are the correct answers of items E217532, E232686, E234938 and E234162; ne are the changes reported in PIE-443 +export default { + mode: "symbolic", + tests: [ + { + label: "E217532: $target", + target: + "\\frac{\\left(y+0\\right)^2}{16}-\\frac{\\left(x+2\\right)^2}{9}=1", + eq: [ + "\\frac{y^2}{16}-\\frac{(x+2)^2}{9}=1", + "-\\frac{(x+2)^2}{9}+\\frac{y^2}{16}=1", + "1=\\frac{y^2}{16}-\\frac{(x+2)^2}{9}", + "9y^2-16(x+2)^2=144", + "9y^2-16x^2-64x-64=144", + "9y^2-16x^2-64x-208=0", + "\\frac{(x+2)^2}{9}-\\frac{y^2}{16}=-1", + ], + ne: [ + // change either or both of the exponents + "\\frac{\\left(y+0\\right)^3}{16}-\\frac{\\left(x+2\\right)^2}{9}=1", + "\\frac{\\left(y+0\\right)^2}{16}-\\frac{\\left(x+2\\right)^3}{9}=1", + "\\frac{\\left(y+0\\right)^3}{16}-\\frac{\\left(x+2\\right)^3}{9}=1", + // change y+0 to 2y+4 + "\\frac{\\left(2y+4\\right)^2}{16}-\\frac{\\left(x+2\\right)^2}{9}=1", + // change 16 to 17 + "\\frac{\\left(y+0\\right)^2}{17}-\\frac{\\left(x+2\\right)^2}{9}=1", + // change x+2 to 3x+7 + "\\frac{\\left(y+0\\right)^2}{16}-\\frac{\\left(3x+7\\right)^2}{9}=1", + // change 9 to 11 + "\\frac{\\left(y+0\\right)^2}{16}-\\frac{\\left(x+2\\right)^2}{11}=1", + // change 1 to 5 + "\\frac{\\left(y+0\\right)^2}{16}-\\frac{\\left(x+2\\right)^2}{9}=5", + // change a variable + "\\frac{\\left(a+0\\right)^2}{16}-\\frac{\\left(x+2\\right)^2}{9}=1", + ], + }, + { + label: "E232686: $target", + target: "\\left(y-7\\right)^2=60\\left(x-15\\right)", + eq: [ + "60(x-15)=(y-7)^2", + "y^2-14y+49=60x-900", + "y^2-14y-60x+949=0", + "\\frac{(y-7)^2}{60}=x-15", + "x=\\frac{(y-7)^2}{60}+15", + ], + ne: [ + // change the exponent 2 to 3 + "\\left(y-7\\right)^3=60\\left(x-15\\right)", + // change y-7 to 2y-8 + "\\left(2y-8\\right)^2=60\\left(x-15\\right)", + // change 60 to 40 + "\\left(y-7\\right)^2=40\\left(x-15\\right)", + // change x-15 to 4x-14 + "\\left(y-7\\right)^2=60\\left(4x-14\\right)", + // add an exponent 2 to (x-15) + "\\left(y-7\\right)^2=60\\left(x-15\\right)^2", + // change a variable + "\\left(a-7\\right)^2=60\\left(x-15\\right)", + ], + }, + { + label: "E234938: $target", + target: "\\frac{x^2}{64}+\\frac{y^2}{36}=1", + eq: [ + // the item's alternate correct answer + "36x^2+64y^2=2,304", + "\\frac{y^2}{36}+\\frac{x^2}{64}=1", + "1=\\frac{x^2}{64}+\\frac{y^2}{36}", + "9x^2+16y^2=576", + "36x^2+64y^2-2304=0", + "\\frac{x^2}{64}=1-\\frac{y^2}{36}", + ], + ne: [ + // change x^2 to x^4 + "\\frac{x^4}{64}+\\frac{y^2}{36}=1", + // change 64 to 6 + "\\frac{x^2}{6}+\\frac{y^2}{36}=1", + // change y^2 to 3y^(-2) + "\\frac{x^2}{64}+\\frac{3y^{-2}}{36}=1", + // change 36 to 360 + "\\frac{x^2}{64}+\\frac{y^2}{360}=1", + // change 1 to 3 + "\\frac{x^2}{64}+\\frac{y^2}{36}=3", + // all of the above + "\\frac{x^4}{6}+\\frac{3y^{-2}}{360}=3", + // change a variable + "\\frac{x^2}{64}+\\frac{z^2}{36}=1", + ], + }, + { + label: "E234938 alternate: $target", + target: "36x^2+64y^2=2,304", + eq: ["\\frac{x^2}{64}+\\frac{y^2}{36}=1", "9x^2+16y^2=576"], + ne: [ + "36x^4+64y^2=2,304", + "36x^2+64y^2=2,305", + "36x^2+64y^{-2}=2,304", + ], + }, + { + label: "E234162: $target", + target: "\\frac{\\left(x+10\\right)^2}{275}+\\frac{y^2}{900}=1", + eq: [ + "\\frac{y^2}{900}+\\frac{(x+10)^2}{275}=1", + "1=\\frac{(x+10)^2}{275}+\\frac{y^2}{900}", + "900(x+10)^2+275y^2=247500", + "36(x+10)^2+11y^2=9900", + "36x^2+720x+3600+11y^2=9900", + ], + ne: [ + // change x+10 to 2x+11 + "\\frac{\\left(2x+11\\right)^2}{275}+\\frac{y^2}{900}=1", + // change 275 to 27.5 + "\\frac{\\left(x+10\\right)^2}{27.5}+\\frac{y^2}{900}=1", + // change y^2 to 3y^8 + "\\frac{\\left(x+10\\right)^2}{275}+\\frac{3y^8}{900}=1", + // change 900 to 3 + "\\frac{\\left(x+10\\right)^2}{275}+\\frac{y^2}{3}=1", + // change 1 to 5 + "\\frac{\\left(x+10\\right)^2}{275}+\\frac{y^2}{900}=5", + // change a variable + "\\frac{\\left(x+10\\right)^2}{275}+\\frac{z^2}{900}=1", + ], + }, + { + // both sides multiplied by a denominator that contains a variable + label: "$target", + target: "\\frac{y-1}{x-2}=3", + eq: ["y-1=3(x-2)", "y-1=3x-6", "y=3x-5"], + ne: ["y-1=3(x+2)", "y-1=2(x-2)"], + }, + { + label: "$target", + target: "y=\\frac{2x+1}{x-3}", + eq: ["y(x-3)=2x+1", "xy-3y=2x+1"], + ne: ["y(x-3)=2x-1", "y(x+3)=2x+1"], + }, + { + label: "$target", + target: "y=\\frac{4}{x+3}", + eq: ["xy+3y=4", "y(x+3)=4"], + ne: ["xy+3y=5", "xy=4"], + }, + { + // these only differ for negative values of x or y + label: "$target", + target: "x^3=8", + eq: ["2x^3=16"], + ne: [ + "\\sqrt{x^6}=8", + "\\left|x\\right|^3=8", + "\\left|x^3\\right|=8", + ], + }, + { + label: "$target", + target: "y=x", + eq: ["2y=2x", "y-x=0"], + ne: ["y=\\left|x\\right|", "y=\\sqrt{x^2}", "\\left|y\\right|=x"], + }, + { + // with the function in the target, the numeric check decides + label: "$target", + target: "y=\\left|x\\right|", + ne: ["y=x", "y=-x"], + }, + { + label: "$target", + target: "\\left|x\\right|^3=8", + ne: ["x^3=8"], + }, + { + label: "$target", + target: "y=\\sqrt{x^2}", + ne: ["y=x"], + }, + { + // high powers skip the numerator comparison, which would otherwise take tens of seconds + label: "$target", + target: "\\frac{(x+1)^7}{(y-1)^7}=1", + ne: ["(x+1)^7=2(y-1)^7"], + }, + ], +}; diff --git a/src/fixtures/latex-equal/symbolic/PIE-905.ts b/src/fixtures/latex-equal/symbolic/PIE-905.ts new file mode 100644 index 0000000..ef7d86b --- /dev/null +++ b/src/fixtures/latex-equal/symbolic/PIE-905.ts @@ -0,0 +1,90 @@ +// numbers that differ from the target by less than 0.00005 must not be scored as equal +export default { + mode: "symbolic", + tests: [ + { + target: "800", + eq: ["800.0", "800.00", "400*2", "\\frac{1600}{2}"], + ne: ["800.00001", "799.99999", "800.0001"], + }, + { + target: "800", + mode: "literal", + ne: ["800.00001"], + }, + { + target: "-800", + eq: ["-800.0", "-400*2"], + ne: ["-800.00001", "-799.99999"], + }, + { + target: "100", + eq: ["10^2", "100.000"], + ne: ["100.000001"], + }, + { + target: "10^2", + eq: ["100"], + ne: ["100.00001"], + }, + { + target: "1000000", + ne: ["1000000.0001"], + }, + { + target: "\\sqrt{2}", + eq: ["\\frac{2}{\\sqrt{2}}", "\\sin(45°)\\cdot 2"], + ne: ["1.4142", "1.41421356237"], + }, + { + target: "\\frac{\\sqrt{3}}{2}", + eq: ["\\sin(60°)", "\\cos(30°)", "\\sin(\\frac{\\pi}{3})"], + ne: ["0.866", "0.86603"], + }, + // values below 1 need the same number of matching digits as larger ones + { + target: "\\frac{1}{3}", + eq: ["\\frac{2}{6}"], + ne: ["0.333333333333", "0.3333"], + }, + { + target: "\\frac{1}{7}", + ne: ["0.142857142857", "0.142857"], + }, + { + target: "0", + eq: ["\\sin(2\\pi)", "\\cos(270°)", "\\sin(3600°)"], + ne: ["0.0000000000001", "0.00001"], + }, + // floating-point noise from pi and angle conversions is still accepted + { + target: "0.5", + eq: ["\\sin(30°)", "\\cos(60°)", "-\\cos(\\frac{2\\pi}{3})"], + }, + { + target: "\\sqrt{3}", + eq: ["\\tan(60°)"], + }, + { + target: "0.3", + eq: ["0.1+0.2"], + }, + { + target: "1000", + eq: ["1000\\tan(45°)"], + }, + // angles in degrees, radians and gradians are converted with the exact value of pi + { + target: "30°", + eq: ["\\arcsin(0.5)"], + }, + { + target: "\\frac{\\pi}{2}", + eq: ["90°", "100\\grad"], + }, + { + target: "\\pi", + eq: ["180°"], + }, + ], +}; diff --git a/src/fixtures/latex-equal/symbolic/math-evaluator.ts b/src/fixtures/latex-equal/symbolic/math-evaluator.ts index 137ba45..ea69995 100644 --- a/src/fixtures/latex-equal/symbolic/math-evaluator.ts +++ b/src/fixtures/latex-equal/symbolic/math-evaluator.ts @@ -13,7 +13,7 @@ export default { "10*10", "100 / 2 + 50", ], - // ne: ["100.000001", "44 + 57", "50 * 3", "25 * 2 + 51"], + ne: ["100.000001", "44 + 57", "50 * 3", "25 * 2 + 51"], }, { target: "13/2", diff --git a/src/symbolic/compare-equations.ts b/src/symbolic/compare-equations.ts index 2dbcd36..9e5178c 100644 --- a/src/symbolic/compare-equations.ts +++ b/src/symbolic/compare-equations.ts @@ -5,12 +5,12 @@ import { equationsHaveTheSameVariables, getCoefficients, solveLinearEquation, - setXToOne, transformEqualityInExpression, expressionsCanBeCompared, solveQuadraticEquation, hasSymbolicExponent, areNumericallyEquivalent, + areEquationsNumericallyEquivalent, } from "./utils"; const m: any = mathjs; @@ -142,27 +142,31 @@ export const compareEquations = ( equivalence = solutionForFirstEquation === solutionForSecondEquation && solutionForFirstEquation !== undefined; + + // equations that are neither linear nor quadratic can't be solved above; compare them numerically instead + if ( + !isInequality && + (solutionForFirstEquation === undefined || + solutionForSecondEquation === undefined) + ) { + return areEquationsNumericallyEquivalent( + firstExpression, + secondExpression, + firstEquationVariablesName + ); + } } - // if both equations are linear in two variabled then we give value "1" for both "x". Doing this we get a linear equation in one variable "y". Then we solve "y" for both. If y has the same value then equations are equivalent + // equations in two variables describe the same curve when one is a multiple of the other; + // checking a single value of x is not enough, and fails for equations that are not linear in y (PIE-443) + // inequalities describe the same region only when the multiple is positive, since a negative one would flip the sign (PIE-1419) if (firstEquationVariablesName.length === 2) { - let x = firstEquationVariablesName[0]; - - // solve expression for x=1 - let expraNoX = setXToOne(firstExpression, x); - firstEquationCoefficients = getCoefficients(expraNoX, isInequality); - - let exprbNoX = setXToOne(secondExpression, x); - secondEquationCoefficients = getCoefficients(exprbNoX, isInequality); - - // find y for both equations, where x equals 1 - let yFromFirstExpression = solveLinearEquation(firstEquationCoefficients); - let yFromSecondExpression = solveLinearEquation( - secondEquationCoefficients + return areEquationsNumericallyEquivalent( + firstExpression, + secondExpression, + firstEquationVariablesName, + { allowVariableFactor: true, positiveOnly: isInequality } ); - - // if y has the same value, for the same x then the expressions should be equivalent - equivalence = yFromFirstExpression === yFromSecondExpression; } // determine equivalence between 2-way inequalities with 1 or 2 variables: diff --git a/src/symbolic/index.ts b/src/symbolic/index.ts index 1e14c72..eeccaba 100644 --- a/src/symbolic/index.ts +++ b/src/symbolic/index.ts @@ -1,14 +1,27 @@ import { logger } from "../log"; import { mathjs } from "../mathjs"; -import { MathNode } from "mathjs"; +import { all, create, MathNode } from "mathjs"; import { sort } from "../node-sort"; import { compareEquations } from "./compare-equations"; import { compareCompoundInequations } from "./compare-compound-inequations"; const m: any = mathjs; const log = logger("mv:symbolic"); -const positiveInfinity = 1.497258191621251e6; -const negativeInfinity = -1.497258191621251e6; + +// an angle counts as k quarter turns (90°, 180°, ...) only when it is one up to floating-point error, +// which keeps angles that are only close, like 89.9999°, 1.5708 or 9090.001°, from being matched +const ANGLE_TOLERANCE = 1e-9; + +// angles are evaluated as plain numbers, the Fraction config used elsewhere cannot represent pi +const numeric: any = create(all); + +// tolerances for floating-point noise from trig functions, pi and angle conversions (PIE-905); +// the noise grows with the angle, e.g. sin(2pi) = -2.4e-16, sin(200pi) = 3.9e-15, tan(36045°) - 1 = -5.4e-14, +// so a value is accepted only when it agrees with the target to about 13 significant digits +const RELATIVE_EPSILON = 1e-13; +// floor for comparisons with 0, where a relative tolerance alone would require an exact match; +// it covers residues such as sin(200pi) and cos(100.5pi) while still rejecting 0 vs 0.0000000000001 +const ABSOLUTE_EPSILON = 1e-14; export type SymbolicOpts = {}; @@ -70,8 +83,110 @@ export const simplify = (v) => { return ms(v, rules); //.concat(SIMPLIFY_RULES)); }; +const hasSymbol = (node: MathNode, matches: (name: string) => boolean) => { + let found = false; + + // the name of a function such as sqrt is a symbol too, under the path "fn" + node.traverse((n: any, path: string) => { + found = found || (n.isSymbolNode && path !== "fn" && matches(n.name)); + }); + + return found; +}; + +// evaluates a constant expression as a plain number, undefined if it has variables; +// any symbol other than pi and Infinity is a variable, even names mathjs knows as constants such as e, E or phi +const evaluateNumber = (node: MathNode): number | undefined => { + if (hasSymbol(node, (name) => name !== "pi" && name !== "Infinity")) { + return undefined; + } + + try { + const value = numeric.evaluate(node.toString()); + return typeof value === "number" ? value : undefined; + } catch (e) { + return undefined; + } +}; + +// returns k when the constant angle is (within tolerance) a multiple k of pi/2 +const quarterTurns = (angle: MathNode): number | undefined => { + const value = evaluateNumber(angle); + + if (value === undefined || !isFinite(value)) { + return undefined; + } + + const turns = value / (Math.PI / 2); + const k = Math.round(turns); + + return Math.abs(turns - k) <= ANGLE_TOLERANCE * Math.max(1, Math.abs(k)) + ? k + : undefined; +}; + +// replace trigonometric functions evaluated at an angle where they are zero or undefined +// with their exact value, so that tan(90°) becomes Infinity instead of a large finite number +const snapTrigonometricValues = (node: MathNode) => { + let changed = false; + + const r: MathNode | any = node.transform((n: any) => { + if (!n.isFunctionNode || n.args?.length !== 1) { + return n; + } + + const k = quarterTurns(n.args[0]); + + if (k === undefined) { + return n; + } + + const odd = Math.abs(k) % 2 === 1; + let snapped = n; + + switch (n.fn.name) { + case "sin": + snapped = odd ? n : new m.ConstantNode(0); + break; + case "cos": + snapped = odd ? new m.ConstantNode(0) : n; + break; + case "tan": + snapped = odd ? new m.SymbolNode("Infinity") : new m.ConstantNode(0); + break; + case "cot": + snapped = odd ? new m.ConstantNode(0) : new m.SymbolNode("Infinity"); + break; + case "sec": + snapped = odd ? new m.SymbolNode("Infinity") : n; + break; + case "csc": + snapped = odd ? n : new m.SymbolNode("Infinity"); + break; + } + + changed = changed || snapped !== n; + + return snapped; + }); + + // keep the original node when nothing was replaced, later steps rely on its identity + return { r: changed ? r : node, changed }; +}; + const normalize = (a: string | MathNode | any) => { - let r: string | MathNode | any = a; + const snapped = snapTrigonometricValues(a); + let r: string | MathNode | any = snapped.r; + + // simplify and rationalize treat Infinity as a variable (1 / Infinity + 3 becomes (1 + 3 * Infinity) / Infinity) + // and keep the sign of a division by zero, so a constant expression with an Infinity or a division by zero is evaluated before it is normalized; + // other constant expressions keep their exact value, such as 1/3 in sin(0) + 1/3 + const snappedValue = snapped.changed ? evaluateNumber(r) : undefined; + const valueWithSnappedTrigonometry = + snappedValue !== undefined && + (!isFinite(snappedValue) || hasSymbol(r, (name) => name === "Infinity")) + ? snappedValue + : undefined; let onlyConstant = true; let containsFunctionNode = false; let containsArrayNode = false; @@ -147,27 +262,50 @@ const normalize = (a: string | MathNode | any) => { log("[normalize] input: ", a.toString(), "output: ", r.toString()); - // check for infinity - if ( - r.toString() === "Infinity" || - +r.toString() >= positiveInfinity || - +r.toString() <= negativeInfinity - ) { - r = new m.SymbolNode("Infinity"); + // an undefined value has no sign, so -tan(90°) and -1/cos(90°) are Infinity as well; + // an indeterminate result such as tan(90°) - tan(90°) or 0 * tan(90°) is NaN and must not simplify to a number + if (valueWithSnappedTrigonometry !== undefined) { + r = isNaN(valueWithSnappedTrigonometry) + ? new m.SymbolNode("NaN") + : isFinite(valueWithSnappedTrigonometry) + ? new m.ConstantNode(valueWithSnappedTrigonometry) + : new m.SymbolNode("Infinity"); } - if (r.value) { - r.value = new m.Fraction(Math.round(r.value * 10000) / 10000); - } else if (r.fn === "unaryMinus") { - r.args[0].value = new m.Fraction( - Math.round(r.args[0].value * 10000) / 10000 - ); - r = simplify(r); + if (r.toString() === "Infinity") { + r = new m.SymbolNode("Infinity"); } return r; }; +// numeric value of an expression without variables, such as 5, -5 or -1/2; undefined for anything else +const constantValue = (node: any): number | undefined => { + if (node.filter((n) => n.isSymbolNode).length > 0) { + return undefined; + } + + try { + const result = node.evaluate(); + + // equations and inequalities without variables evaluate to booleans + if (typeof result === "boolean") { + return undefined; + } + + const value = +result; + return Number.isFinite(value) ? value : undefined; + } catch (e) { + return undefined; + } +}; + +const areNearlyEqual = (a: number, b: number) => + Math.abs(a - b) < + ABSOLUTE_EPSILON + RELATIVE_EPSILON * Math.max(Math.abs(a), Math.abs(b)); + +const isIndeterminate = (node: any) => node?.isSymbolNode && node.name === "NaN"; + export const isMathEqual = (a: any, b: any) => { let as: MathNode; let bs: MathNode; @@ -202,6 +340,11 @@ export const isMathEqual = (a: any, b: any) => { log("[isMathEqual]", as.toString(), "==?", bs.toString()); + // an indeterminate result such as tan(90°) - tan(90°) is not equal to anything, not even another indeterminate result + if (isIndeterminate(as) || isIndeterminate(bs)) { + return false; + } + const isSortingEnough = sort(a).equals(sort(b)); const isTexEnough = as.toTex().trim() === bs.toTex().trim(); @@ -211,6 +354,14 @@ export const isMathEqual = (a: any, b: any) => { return true; } + // compare constant results numerically, allowing only for floating-point noise + const aValue = constantValue(as); + const bValue = constantValue(bs); + + if (aValue !== undefined && bValue !== undefined) { + return areNearlyEqual(aValue, bValue); + } + // if both expressions are equations if (as.fn === "equal" && bs.fn === "equal") { return compareEquations(as, bs, false); diff --git a/src/symbolic/utils.ts b/src/symbolic/utils.ts index 07cca9c..c29fe39 100644 --- a/src/symbolic/utils.ts +++ b/src/symbolic/utils.ts @@ -1,10 +1,13 @@ import { mathjs } from "../mathjs"; -import { MathNode } from "mathjs"; +import { all, create, MathNode } from "mathjs"; import { simplify as customSimplify } from "./"; const { simplify } = mathjs; const m: any = mathjs; +// plain floating-point instance for numeric checks; the shared instance works with fractions +const numeric: any = create(all); + let simplifyRules = [ { l: "-((n1)*(n2))", r: "(n1)*(n2)" }, { l: "(n1-n2)/n3", r: "n1/n3-n2/n3" }, @@ -62,31 +65,236 @@ export const hasSymbolicExponent = (node: MathNode): boolean => { return found; }; +// deterministic pseudo-random generator (mulberry32), so numeric checks give the same result on every run +const seededRandom = (seed: number) => () => { + seed = (seed + 0x6d2b79f5) | 0; + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; +}; + +// sample points where every variable gets its own non-integer value between 0.5 and 4.5 in size, +// so that expressions like x^2 and y^2 can be told apart; the sign is random too, +// so that expressions like |x| and x, or sqrt(x^6) and x^3, can be told apart +export const getSamplePoints = (variables: string[], count: number = 12) => { + const random = seededRandom(443); + + return Array.from({ length: count }, () => + variables.reduce((acc, v) => { + const size = 0.5 + 4 * random(); + acc[v] = random() < 0.5 ? -size : size; + return acc; + }, {} as Record) + ); +}; + +// evaluate an expression at each sample point; NaN where it can't be evaluated to a real number +const evaluateAtPoints = (expr: MathNode, points: Record[]) => { + let compiled: any; + + try { + compiled = numeric.compile(expr.toString()); + } catch { + return points.map(() => NaN); + } + + return points.map((scope) => { + try { + const result = compiled.evaluate({ ...scope }); + return typeof result === "number" ? result : NaN; + } catch { + return NaN; + } + }); +}; + +const areClose = (a: number, b: number, tolerance: number) => + Math.abs(a - b) <= tolerance * Math.max(1, Math.abs(a), Math.abs(b)); + +// points where either side can't be evaluated to a real number (e.g. sqrt of a negative number) are skipped export const areNumericallyEquivalent = ( exprA: MathNode, exprB: MathNode, variables: string[], tolerance: number = 1e-10 ): boolean => { - const compiledA = m.compile(exprA.toString()); - const compiledB = m.compile(exprB.toString()); + const points = getSamplePoints(variables); + const valuesA = evaluateAtPoints(exprA, points); + const valuesB = evaluateAtPoints(exprB, points); - const testValues = [1, 2, 3, 4, 5]; + const compared = valuesA.filter( + (a, i) => Number.isFinite(a) && Number.isFinite(valuesB[i]) + ); - return testValues.every((val) => { - const scope = variables.reduce((acc, v) => { - acc[v] = val; - return acc; - }, {} as Record); + return ( + compared.length >= 3 && + valuesA.every( + (a, i) => + !Number.isFinite(a) || + !Number.isFinite(valuesB[i]) || + areClose(a, valuesB[i], tolerance) + ) + ); +}; - try { - const resultA = compiledA.evaluate(scope); - const resultB = compiledB.evaluate(scope); - return Math.abs(resultA - resultB) < tolerance; - } catch { +// exponent combinations for a factor such as x, 1/y or x*y^2, used when both sides of an equation were multiplied by variables +const getVariableFactors = (variables: string[], maxPower: number) => + variables.reduce( + (factors, v) => + factors.reduce( + (acc, factor) => + acc.concat( + Array.from({ length: 2 * maxPower + 1 }, (_, i) => ({ + ...factor, + [v]: i - maxPower, + })) + ), + [] as Record[] + ), + [{}] as Record[] + ); + +const haveProportionalValues = ( + firstExpression: MathNode, + secondExpression: MathNode, + variables: string[], + { + allowVariableFactor = false, + positiveOnly = false, + }: { allowVariableFactor?: boolean; positiveOnly?: boolean } = {} +): boolean => { + const tolerance = 1e-9; + const points = getSamplePoints(variables); + const firstValues = evaluateAtPoints(firstExpression, points); + const secondValues = evaluateAtPoints(secondExpression, points); + + const ratios: { point: Record; ratio: number }[] = []; + + for (let i = 0; i < points.length; i++) { + const f = firstValues[i]; + const g = secondValues[i]; + + if (!Number.isFinite(f) || !Number.isFinite(g)) { + continue; + } + + const fIsZero = Math.abs(f) < tolerance; + const gIsZero = Math.abs(g) < tolerance; + + // the point lies on both curves + if (fIsZero && gIsZero) { + continue; + } + + // the point lies on only one of the curves + if (fIsZero || gIsZero) { return false; } + + ratios.push({ point: points[i], ratio: f / g }); + } + + // not enough points to decide + if (ratios.length < 3) { + return false; + } + + // for inequalities only even powers are allowed, since an odd power of a variable can be negative and reverse the sign + const factors = allowVariableFactor + ? getVariableFactors(variables, 2).filter( + (factor) => + !positiveOnly || Object.values(factor).every((power) => power % 2 === 0) + ) + : [{} as Record]; + + return factors.some((factor) => { + const scaled = ratios.map(({ point, ratio }) => + Object.keys(factor).reduce( + (acc, v) => acc / Math.pow(point[v], factor[v]), + ratio + ) + ); + + return ( + (!positiveOnly || scaled[0] > 0) && + scaled.every((r) => areClose(r, scaled[0], tolerance)) + ); + }); +}; + +// the numerator N of F written as a single fraction N/D, or undefined when F has no variable denominator; +// F = 0 exactly where N = 0, so this undoes both sides being multiplied by an expression such as x-2 +// rationalize expands powers, which gets very slow for high powers or long expressions, so those are left as they are +const MAX_NUMERATOR_POWER = 4; +const MAX_NUMERATOR_NODES = 60; + +const isTooLargeToRationalize = (expr: MathNode) => { + let nodes = 0; + let tooLarge = false; + + expr.traverse((n: any) => { + nodes++; + tooLarge = + tooLarge || + (n.isOperatorNode && + n.op === "^" && + n.args[1]?.isConstantNode && + Math.abs(Number(n.args[1].value)) > MAX_NUMERATOR_POWER); }); + + return tooLarge || nodes > MAX_NUMERATOR_NODES; +}; + +const getNumerator = (expr: MathNode): MathNode | undefined => { + if (isTooLargeToRationalize(expr)) { + return undefined; + } + + try { + const { numerator, denominator } = numeric.rationalize( + expr.toString(), + {}, + true + ); + + return denominator ? numerator : undefined; + } catch { + return undefined; + } +}; + +// two equations F = 0 and G = 0 describe the same solutions when F is a nonzero constant multiple of G; +// with allowVariableFactor, F may also be G multiplied by a power of each variable (e.g. both sides multiplied by x) +// set positiveOnly for inequalities, where multiplying by a negative number reverses the sign +export const areEquationsNumericallyEquivalent = ( + firstExpression: MathNode, + secondExpression: MathNode, + variables: string[], + options: { allowVariableFactor?: boolean; positiveOnly?: boolean } = {} +): boolean => { + if ( + haveProportionalValues(firstExpression, secondExpression, variables, options) + ) { + return true; + } + + // multiplying both sides of an inequality by an expression may reverse the sign, so only equations compare numerators + if (options.positiveOnly) { + return false; + } + + const firstNumerator = getNumerator(firstExpression); + const secondNumerator = getNumerator(secondExpression); + + return ( + (firstNumerator !== undefined || secondNumerator !== undefined) && + haveProportionalValues( + firstNumerator || firstExpression, + secondNumerator || secondExpression, + variables, + options + ) + ); }; // move the terms of the equations to the left hand side @@ -142,15 +350,6 @@ export const getCoefficients = (equation: MathNode, isInequality: boolean) => { return [1, 0]; }; -export const setXToOne = (equation: any, variableName: string) => - equation.transform(function (node, path, parent) { - if (node.isSymbolNode && node.name === variableName) { - return new m.ConstantNode(1); - } - - return node; - }); - // quadratic equation solver for a second-order polynomial equation such as ax^2 + bx + c = 0 for x, where a is not zero // quadratic formula export const solveQuadraticEquation = (coefficients: number[]) => { diff --git a/yarn.lock b/yarn.lock index 91e5353..e24d9d4 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4841,9 +4841,9 @@ js-tokens@^4.0.0: integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== js-yaml@^3.13.1: - version "3.14.0" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.14.0.tgz#a7a34170f26a21bb162424d8adacb4113a69e482" - integrity sha512-/4IbIeHcD9VMHFqDR/gQ7EdZdLimOvW2DdcxFjdyyZ9NsbS+ccrXqVWDtab/lRl5AlUqmpBx8EhPaWR+OtY17A== + version "3.14.2" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.14.2.tgz#77485ce1dd7f33c061fd1b16ecea23b55fcb04b0" + integrity sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg== dependencies: argparse "^1.0.7" esprima "^4.0.0" @@ -5225,9 +5225,9 @@ lodash.uniqby@^4.7.0: integrity sha1-2ZwHpmnp5tJOE2Lf4mbGdhavEwI= lodash@^4.17.13, lodash@^4.17.15, lodash@^4.17.21, lodash@^4.17.4: - version "4.17.21" - resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" - integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== + version "4.17.23" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.23.tgz#f113b0378386103be4f6893388c73d0bde7f2c5a" + integrity sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w== lru-cache@^10.0.1: version "10.4.3"