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/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/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/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[]) => {