forked from Blendman974/faceclaw
Add calculator and microphone conversation apps
Add symbolic math and graphing tools, dual-microphone audio processing, live captions, translation, speaker diarization, sentiment analysis, and searchable conversation history. Extend Android voice and BLE support for microphone control, recording, transcoding, and on-device speaker identification, with coverage for calculator and microphone workflows.
This commit is contained in:
124 files changed
+22061
-58
No files matched your search
@@ -0,0 +1,796 @@
|
||||
// Routes a spoken question to the right advanced-maths topic. Separate from
|
||||
// the command parser because these questions have a different shape: a
|
||||
// command is about an EXPRESSION and what to do with it, whereas "is 91
|
||||
// prime", "factor 360", "area of a circle with radius 3" name a topic and
|
||||
// carry their own arguments. Trying to force both through one parser made
|
||||
// the expression grammar swallow phrases it had no business touching.
|
||||
|
||||
import { type MathExpression, variablesOf } from "./expression";
|
||||
import { parseSpoken } from "./parser";
|
||||
import { applyNumberWords } from "./normalizer";
|
||||
import { plain } from "./text-renderer";
|
||||
import { describeNumber, formatInt, fromDecimal } from "./math-number";
|
||||
import {
|
||||
type MathConstantName,
|
||||
MAXIMUM_COMPUTED_DIGITS,
|
||||
constantDisplayName,
|
||||
constantNamed,
|
||||
constantSpokenName,
|
||||
} from "./constant-digits";
|
||||
import {
|
||||
countDigits as countDigitsIn,
|
||||
digitsAt,
|
||||
expectedFirstPosition,
|
||||
findDigits,
|
||||
highlightedMatch,
|
||||
} from "./digit-search";
|
||||
import { type MathWorkload, longRunOffer as makeLongRunOffer, type LongRunOffer } from "./workload";
|
||||
import {
|
||||
binomial,
|
||||
factorizationText,
|
||||
fibonacci,
|
||||
greatestCommonDivisor,
|
||||
integerReport,
|
||||
isPrime,
|
||||
leastCommonMultiple,
|
||||
modularInverse,
|
||||
} from "./number-theory";
|
||||
import {
|
||||
type Shape,
|
||||
pythagoras,
|
||||
shapeName,
|
||||
shapeSummary,
|
||||
triangleAnglesInDegrees,
|
||||
triangleArea,
|
||||
triangleFromSides,
|
||||
triangleKind,
|
||||
trianglePerimeter,
|
||||
} from "./geometry";
|
||||
import { TRIG_IDENTITIES, familyText, identityMatching, solveTrig } from "./trigonometry";
|
||||
import { criticalPointText, criticalPoints, limit, limitText, taylor } from "./calculus";
|
||||
import { definite, integrateWithConstant } from "./symbolic-integral";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Topics
|
||||
|
||||
export type AdvancedTopic =
|
||||
| { kind: "integerReport"; value: number }
|
||||
| { kind: "primality"; value: number }
|
||||
| { kind: "factorize"; value: number }
|
||||
| { kind: "gcd"; a: number; b: number }
|
||||
| { kind: "lcm"; a: number; b: number }
|
||||
| { kind: "modularInverse"; value: number; modulus: number }
|
||||
| { kind: "fibonacci"; n: number }
|
||||
| { kind: "binomial"; n: number; k: number }
|
||||
| { kind: "symbolicIntegral"; expression: MathExpression; variable: string }
|
||||
| { kind: "definiteIntegral"; expression: MathExpression; variable: string; from: number; to: number }
|
||||
| { kind: "limit"; expression: MathExpression; variable: string; at: number }
|
||||
| { kind: "taylor"; expression: MathExpression; variable: string; order: number }
|
||||
| { kind: "criticalPoints"; expression: MathExpression; variable: string }
|
||||
| { kind: "trigSolve"; fn: "sin" | "cos" | "tan"; value: number }
|
||||
| { kind: "trigIdentity"; query: string }
|
||||
/** "where does 11 first appear in pi" */
|
||||
| { kind: "digitSearch"; pattern: string; constant: MathConstantName; occurrence: number }
|
||||
/** "how many times does 42 appear in pi" */
|
||||
| { kind: "digitCount"; pattern: string; constant: MathConstantName }
|
||||
/** "what are digits 100 to 110 of pi" */
|
||||
| { kind: "digitsAt"; constant: MathConstantName; from: number; to: number }
|
||||
| { kind: "shapeArea"; shape: Shape }
|
||||
| { kind: "triangleFromSides"; a: number; b: number; c: number }
|
||||
| { kind: "pythagoras"; a: number | null; b: number | null; c: number | null };
|
||||
|
||||
export type AdvancedAnswer = {
|
||||
headline: string;
|
||||
detail: string;
|
||||
/** Extra rows for the answer view, and for a longer readback. */
|
||||
fields: [string, string][];
|
||||
/**
|
||||
* Set when this answer is only as good as the fast expansion allowed, and
|
||||
* a deeper opted-in run would do better. The router itself never starts
|
||||
* one: it is pure and synchronous, and the wait is a decision belonging to
|
||||
* the caller.
|
||||
*/
|
||||
unresolvedWorkload: MathWorkload | null;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Parsing
|
||||
|
||||
/**
|
||||
* null when the utterance is not an advanced-maths question, so the caller
|
||||
* can fall through to the ordinary expression path.
|
||||
*/
|
||||
export function parseAdvanced(utterance: string): AdvancedTopic | null {
|
||||
const text = applyNumberWords(utterance.toLowerCase()).replace(/^[ .,!?]+|[ .,!?]+$/g, "");
|
||||
|
||||
// Constants first: "the first 11 in pi" contains digits and the word "in",
|
||||
// which the geometry and number-theory matchers would both take a swing at.
|
||||
const constantTopic = parseConstantDigits(text);
|
||||
if (constantTopic) return constantTopic;
|
||||
const numberTopic = parseNumberTheory(text);
|
||||
if (numberTopic) return numberTopic;
|
||||
const calculusTopic = parseCalculus(text, utterance);
|
||||
if (calculusTopic) return calculusTopic;
|
||||
const trigTopic = parseTrigonometry(text);
|
||||
if (trigTopic) return trigTopic;
|
||||
return parseGeometry(text);
|
||||
}
|
||||
|
||||
// Constant digits ------------------------------------------------------------
|
||||
|
||||
function parseConstantDigits(text: string): AdvancedTopic | null {
|
||||
// Must name a constant AND talk about its expansion, or "area of a circle"
|
||||
// (which contains pi implicitly) would land here.
|
||||
const constant = constantNamed(text);
|
||||
if (!constant) return null;
|
||||
const mentionsDigits =
|
||||
text.includes("digit") ||
|
||||
text.includes("appear") ||
|
||||
text.includes("occur") ||
|
||||
text.includes("within") ||
|
||||
text.includes("inside") ||
|
||||
text.includes("expansion") ||
|
||||
text.includes("decimal place") ||
|
||||
text.includes("position") ||
|
||||
text.includes("show up") ||
|
||||
text.includes("found in");
|
||||
if (!mentionsDigits) return null;
|
||||
|
||||
const numbers = allInts(text);
|
||||
|
||||
// "digits 100 to 110 of pi"
|
||||
if (
|
||||
text.includes("digit") &&
|
||||
text.includes(" to ") &&
|
||||
numbers.length >= 2 &&
|
||||
!text.includes("appear") &&
|
||||
!text.includes("occur")
|
||||
) {
|
||||
const sorted = [numbers[0]!, numbers[1]!].sort((a, b) => a - b);
|
||||
return { kind: "digitsAt", constant, from: sorted[0]!, to: sorted[1]! };
|
||||
}
|
||||
|
||||
// "how many times does 42 appear"
|
||||
if (text.includes("how many") || text.includes("count")) {
|
||||
const pattern = numbers[0];
|
||||
if (pattern === undefined) return null;
|
||||
return { kind: "digitCount", pattern: String(pattern), constant };
|
||||
}
|
||||
|
||||
const pattern = numbers[0];
|
||||
if (pattern === undefined) return null;
|
||||
// "the third time 11 appears"
|
||||
const occurrence = ordinalIn(text) ?? 1;
|
||||
return { kind: "digitSearch", pattern: String(pattern), constant, occurrence };
|
||||
}
|
||||
|
||||
/**
|
||||
* "3rd", not "3th". Cheap to get right and jarring to get wrong on a line
|
||||
* someone reads aloud.
|
||||
*/
|
||||
export function ordinalWord(value: number): string {
|
||||
switch (value) {
|
||||
case 1:
|
||||
return "first";
|
||||
case 2:
|
||||
return "second";
|
||||
case 3:
|
||||
return "third";
|
||||
default:
|
||||
break;
|
||||
}
|
||||
let suffix: string;
|
||||
const mod100 = value % 100;
|
||||
const mod10 = value % 10;
|
||||
if (mod100 === 11 || mod100 === 12 || mod100 === 13) suffix = "th";
|
||||
else if (mod10 === 1) suffix = "st";
|
||||
else if (mod10 === 2) suffix = "nd";
|
||||
else if (mod10 === 3) suffix = "rd";
|
||||
else suffix = "th";
|
||||
return `${value}${suffix}`;
|
||||
}
|
||||
|
||||
function ordinalIn(text: string): number | null {
|
||||
const words: [string, number][] = [
|
||||
["first", 1],
|
||||
["second", 2],
|
||||
["third", 3],
|
||||
["fourth", 4],
|
||||
["fifth", 5],
|
||||
["sixth", 6],
|
||||
["seventh", 7],
|
||||
["eighth", 8],
|
||||
["ninth", 9],
|
||||
["tenth", 10],
|
||||
];
|
||||
for (const [word, value] of words) {
|
||||
if (text.includes(word)) return value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Number theory --------------------------------------------------------------
|
||||
|
||||
function parseNumberTheory(text: string): AdvancedTopic | null {
|
||||
if (text.includes("prime") && !text.includes("factor")) {
|
||||
const value = firstInt(text);
|
||||
if (value !== null) return { kind: "primality", value };
|
||||
}
|
||||
if (text.includes("factor")) {
|
||||
const value = firstInt(text);
|
||||
if (value !== null) return { kind: "factorize", value };
|
||||
}
|
||||
if (text.includes("gcd") || text.includes("greatest common") || text.includes("highest common")) {
|
||||
const values = allInts(text);
|
||||
if (values.length >= 2) return { kind: "gcd", a: values[0]!, b: values[1]! };
|
||||
}
|
||||
if (
|
||||
text.includes("lcm") ||
|
||||
text.includes("lowest common multiple") ||
|
||||
text.includes("least common multiple")
|
||||
) {
|
||||
const values = allInts(text);
|
||||
if (values.length >= 2) return { kind: "lcm", a: values[0]!, b: values[1]! };
|
||||
}
|
||||
if (text.includes("inverse") && text.includes("mod")) {
|
||||
const values = allInts(text);
|
||||
if (values.length >= 2) return { kind: "modularInverse", value: values[0]!, modulus: values[1]! };
|
||||
}
|
||||
if (text.includes("fibonacci")) {
|
||||
const value = firstInt(text);
|
||||
if (value !== null) return { kind: "fibonacci", n: value };
|
||||
}
|
||||
if (text.includes("choose") || text.includes("binomial") || text.includes("combinations")) {
|
||||
const values = allInts(text);
|
||||
if (values.length >= 2) return { kind: "binomial", n: values[0]!, k: values[1]! };
|
||||
}
|
||||
if (text.includes("tell me about") || text.includes("facts about")) {
|
||||
const value = firstInt(text);
|
||||
if (value !== null) return { kind: "integerReport", value };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Calculus -------------------------------------------------------------------
|
||||
|
||||
function parseCalculus(text: string, original: string): AdvancedTopic | null {
|
||||
if (text.includes("integral") || text.includes("integrate") || text.includes("antiderivative")) {
|
||||
const expression = expressionTail(original, ["integral of", "integrate", "antiderivative of", "integral"]);
|
||||
if (!expression) return null;
|
||||
const variable = variablesOf(expression)[0] ?? "x";
|
||||
const bounds = boundsIn(text);
|
||||
if (bounds) {
|
||||
return { kind: "definiteIntegral", expression, variable, from: bounds[0], to: bounds[1] };
|
||||
}
|
||||
return { kind: "symbolicIntegral", expression, variable };
|
||||
}
|
||||
|
||||
if (text.includes("limit")) {
|
||||
const expression = expressionTail(original, ["limit of", "the limit of", "limit"]);
|
||||
if (!expression) return null;
|
||||
// "as x approaches 0"
|
||||
const point = firstDoubleAfter(["approaches", "approaching", "tends to", "goes to"], text) ?? 0;
|
||||
return { kind: "limit", expression, variable: variablesOf(expression)[0] ?? "x", at: point };
|
||||
}
|
||||
|
||||
if (text.includes("taylor") || text.includes("maclaurin") || text.includes("series")) {
|
||||
const expression = expressionTail(original, [
|
||||
"series of",
|
||||
"series for",
|
||||
"expansion of",
|
||||
"taylor",
|
||||
"maclaurin",
|
||||
]);
|
||||
if (!expression) return null;
|
||||
const orderValue = firstDoubleAfter(["order", "to order", "terms"], text);
|
||||
const order = orderValue !== null ? Math.trunc(orderValue) : 5;
|
||||
return { kind: "taylor", expression, variable: variablesOf(expression)[0] ?? "x", order };
|
||||
}
|
||||
|
||||
if (
|
||||
text.includes("critical point") ||
|
||||
text.includes("turning point") ||
|
||||
text.includes("maximum") ||
|
||||
text.includes("minimum") ||
|
||||
text.includes("extrema")
|
||||
) {
|
||||
const expression = expressionTail(original, [
|
||||
"critical points of",
|
||||
"turning points of",
|
||||
"extrema of",
|
||||
"maximum of",
|
||||
"minimum of",
|
||||
"of",
|
||||
]);
|
||||
if (!expression) return null;
|
||||
return { kind: "criticalPoints", expression, variable: variablesOf(expression)[0] ?? "x" };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Trigonometry ---------------------------------------------------------------
|
||||
|
||||
function parseTrigonometry(text: string): AdvancedTopic | null {
|
||||
if (text.includes("identity") || text.includes("law of")) {
|
||||
return { kind: "trigIdentity", query: text };
|
||||
}
|
||||
// "solve sin x = 0.5"
|
||||
for (const name of ["sin", "cos", "tan"] as const) {
|
||||
if (!text.includes(name)) continue;
|
||||
if (!text.includes("=") && !text.includes("equals")) continue;
|
||||
const value = lastDouble(text);
|
||||
if (value === null) continue;
|
||||
return { kind: "trigSolve", fn: name, value };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Geometry -------------------------------------------------------------------
|
||||
|
||||
function parseGeometry(text: string): AdvancedTopic | null {
|
||||
const numbers = allDoubles(text);
|
||||
|
||||
if (text.includes("pythagoras") || text.includes("hypotenuse")) {
|
||||
if (numbers.length < 2) return null;
|
||||
return text.includes("hypotenuse") && text.includes("find")
|
||||
? { kind: "pythagoras", a: numbers[0]!, b: numbers[1]!, c: null }
|
||||
: { kind: "pythagoras", a: numbers[0]!, b: null, c: numbers[1]! };
|
||||
}
|
||||
if (text.includes("triangle") && numbers.length >= 3 && text.includes("side")) {
|
||||
return { kind: "triangleFromSides", a: numbers[0]!, b: numbers[1]!, c: numbers[2]! };
|
||||
}
|
||||
|
||||
// Shapes, longest name first so "rectangular prism" is not read as
|
||||
// "rectangle".
|
||||
const shapes: [string, (values: number[]) => Shape | null][] = [
|
||||
[
|
||||
"rectangular prism",
|
||||
(values) =>
|
||||
values.length >= 3
|
||||
? { kind: "rectangularPrism", length: values[0]!, width: values[1]!, height: values[2]! }
|
||||
: null,
|
||||
],
|
||||
["sphere", (values) => (values.length >= 1 ? { kind: "sphere", radius: values[0]! } : null)],
|
||||
[
|
||||
"cylinder",
|
||||
(values) => (values.length >= 2 ? { kind: "cylinder", radius: values[0]!, height: values[1]! } : null),
|
||||
],
|
||||
["cone", (values) => (values.length >= 2 ? { kind: "cone", radius: values[0]!, height: values[1]! } : null)],
|
||||
["cube", (values) => (values.length >= 1 ? { kind: "cube", side: values[0]! } : null)],
|
||||
["circle", (values) => (values.length >= 1 ? { kind: "circle", radius: values[0]! } : null)],
|
||||
[
|
||||
"rectangle",
|
||||
(values) => (values.length >= 2 ? { kind: "rectangle", width: values[0]!, height: values[1]! } : null),
|
||||
],
|
||||
["square", (values) => (values.length >= 1 ? { kind: "square", side: values[0]! } : null)],
|
||||
[
|
||||
"trapezoid",
|
||||
(values) =>
|
||||
values.length >= 3 ? { kind: "trapezoid", a: values[0]!, b: values[1]!, height: values[2]! } : null,
|
||||
],
|
||||
["ellipse", (values) => (values.length >= 2 ? { kind: "ellipse", a: values[0]!, b: values[1]! } : null)],
|
||||
];
|
||||
const wantsMeasurement =
|
||||
text.includes("area") ||
|
||||
text.includes("volume") ||
|
||||
text.includes("perimeter") ||
|
||||
text.includes("circumference") ||
|
||||
text.includes("surface");
|
||||
if (!wantsMeasurement) return null;
|
||||
for (const [name, build] of shapes) {
|
||||
if (!text.includes(name)) continue;
|
||||
const shape = build(numbers);
|
||||
if (shape) return { kind: "shapeArea", shape };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Answering
|
||||
|
||||
export function answerAdvanced(topic: AdvancedTopic): AdvancedAnswer {
|
||||
switch (topic.kind) {
|
||||
case "integerReport": {
|
||||
const report = integerReport(topic.value);
|
||||
const fields: [string, string][] = [
|
||||
["Prime", report.isPrime ? "yes" : "no"],
|
||||
["Factorisation", factorizationText(report)],
|
||||
["Divisors", String(report.divisorCount)],
|
||||
["Divisor sum", String(report.divisorSum)],
|
||||
["Totient", String(report.totient)],
|
||||
["Digit sum", String(report.digitSum)],
|
||||
["Digital root", String(report.digitalRoot)],
|
||||
];
|
||||
if (report.isPerfect) fields.push(["Perfect", "yes"]);
|
||||
return answer(
|
||||
`${topic.value} = ${factorizationText(report)}`,
|
||||
`${topic.value} is ${report.isPrime ? "prime" : "composite"}, ` +
|
||||
`with ${report.divisorCount} divisors summing to ${report.divisorSum}.`,
|
||||
fields,
|
||||
);
|
||||
}
|
||||
|
||||
case "primality": {
|
||||
const prime = isPrime(topic.value);
|
||||
const report = prime ? "" : factorizationText(integerReport(topic.value));
|
||||
return answer(
|
||||
`${topic.value} is ${prime ? "prime" : "not prime"}`,
|
||||
prime
|
||||
? `${topic.value} has no divisors other than 1 and itself.`
|
||||
: `${topic.value} = ${report}.`,
|
||||
);
|
||||
}
|
||||
|
||||
case "factorize": {
|
||||
const report = integerReport(topic.value);
|
||||
return answer(
|
||||
`${topic.value} = ${factorizationText(report)}`,
|
||||
`${topic.value} factors into ${factorizationText(report)}.`,
|
||||
);
|
||||
}
|
||||
|
||||
case "gcd": {
|
||||
const gcd = greatestCommonDivisor(topic.a, topic.b);
|
||||
return answer(
|
||||
`gcd(${topic.a}, ${topic.b}) = ${gcd}`,
|
||||
`The greatest common divisor of ${topic.a} and ${topic.b} is ${gcd}.`,
|
||||
);
|
||||
}
|
||||
|
||||
case "lcm": {
|
||||
const lcm = leastCommonMultiple(topic.a, topic.b);
|
||||
return answer(
|
||||
`lcm(${topic.a}, ${topic.b}) = ${lcm}`,
|
||||
`The least common multiple of ${topic.a} and ${topic.b} is ${lcm}.`,
|
||||
);
|
||||
}
|
||||
|
||||
case "modularInverse": {
|
||||
const inverse = modularInverse(topic.value, topic.modulus);
|
||||
if (inverse === null) {
|
||||
return answer(
|
||||
"No inverse",
|
||||
`${topic.value} and ${topic.modulus} share a factor, so no modular inverse exists.`,
|
||||
);
|
||||
}
|
||||
return answer(
|
||||
`${topic.value}⁻¹ ≡ ${inverse} (mod ${topic.modulus})`,
|
||||
`${topic.value} × ${inverse} ≡ 1 (mod ${topic.modulus}).`,
|
||||
);
|
||||
}
|
||||
|
||||
case "fibonacci": {
|
||||
const value = fibonacci(topic.n);
|
||||
if (value === null) {
|
||||
return answer("Too large", `F(${topic.n}) does not fit in an exact integer.`);
|
||||
}
|
||||
return answer(`F(${topic.n}) = ${value}`, `The ${topic.n}th Fibonacci number is ${value}.`);
|
||||
}
|
||||
|
||||
case "binomial": {
|
||||
const value = binomial(topic.n, topic.k);
|
||||
if (value === null) {
|
||||
return answer("Undefined", `${topic.n} choose ${topic.k} is not defined.`);
|
||||
}
|
||||
return answer(
|
||||
`C(${topic.n}, ${topic.k}) = ${value}`,
|
||||
`There are ${value} ways to choose ${topic.k} from ${topic.n}.`,
|
||||
);
|
||||
}
|
||||
|
||||
case "symbolicIntegral": {
|
||||
const antiderivative = integrateWithConstant(topic.expression, topic.variable);
|
||||
if (!antiderivative) {
|
||||
return answer(
|
||||
"No closed form",
|
||||
"This has no elementary antiderivative that this build can find. " +
|
||||
"Ask for a definite integral and it will be computed numerically.",
|
||||
);
|
||||
}
|
||||
return answer(
|
||||
`∫ = ${plain(antiderivative)}`,
|
||||
`∫ ${plain(topic.expression)} d${topic.variable} = ${plain(antiderivative)}`,
|
||||
);
|
||||
}
|
||||
|
||||
case "definiteIntegral": {
|
||||
const result = definite(topic.expression, topic.variable, topic.from, topic.to);
|
||||
switch (result.kind) {
|
||||
case "exact":
|
||||
return answer(
|
||||
`∫ = ${describeNumber(result.value)}`,
|
||||
`Using F = ${plain(result.antiderivative)}, the definite integral is ${describeNumber(result.value)}.`,
|
||||
);
|
||||
case "numeric":
|
||||
return answer(
|
||||
`∫ ≈ ${describeNumber(fromDecimal(result.value))}`,
|
||||
"No closed form was found, so this was integrated numerically.",
|
||||
);
|
||||
case "failed":
|
||||
return answer("Could not integrate", result.reason);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "limit": {
|
||||
const result = limit(topic.expression, topic.variable, topic.at);
|
||||
let detail =
|
||||
`As ${topic.variable} → ${format(topic.at)}, ` +
|
||||
`${plain(topic.expression)} → ${limitText(result)}.`;
|
||||
if (result.kind === "doesNotExist") {
|
||||
detail =
|
||||
`The one-sided limits disagree ` +
|
||||
`(${format(result.left ?? 0)} from the left, ${format(result.right ?? 0)} from the right), ` +
|
||||
`so the limit does not exist.`;
|
||||
}
|
||||
return answer(`limit = ${limitText(result)}`, detail);
|
||||
}
|
||||
|
||||
case "taylor": {
|
||||
const series = taylor(topic.expression, topic.variable, topic.order);
|
||||
if (!series) {
|
||||
return answer("No series", "Could not expand that about 0.");
|
||||
}
|
||||
return answer(
|
||||
plain(series),
|
||||
`${plain(topic.expression)} ≈ ${plain(series)} to order ${topic.order}.`,
|
||||
);
|
||||
}
|
||||
|
||||
case "criticalPoints": {
|
||||
const points = criticalPoints(topic.expression, topic.variable);
|
||||
if (points.length === 0) {
|
||||
return answer("No critical points", "The derivative never vanishes in the search window.");
|
||||
}
|
||||
return answer(
|
||||
points
|
||||
.slice(0, 2)
|
||||
.map(criticalPointText)
|
||||
.join(", "),
|
||||
points.map(criticalPointText).join("; "),
|
||||
points.map((point) => [
|
||||
point.kind.charAt(0).toUpperCase() + point.kind.slice(1),
|
||||
`(${format(point.x)}, ${format(point.y)})`,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
case "trigSolve": {
|
||||
const solution = solveTrig(topic.fn, topic.value);
|
||||
switch (solution.kind) {
|
||||
case "none":
|
||||
return answer("No solution", `${topic.fn} never reaches ${format(topic.value)}.`);
|
||||
case "all":
|
||||
return answer("True for every angle", "Any value works.");
|
||||
case "families": {
|
||||
const text = solution.families.map(familyText).join(", ");
|
||||
return answer(
|
||||
`x = ${text}`,
|
||||
`${topic.fn} x = ${format(topic.value)} for x = ${text}, where n is any integer.`,
|
||||
solution.families.map((family, index) => [`Family ${index + 1}`, familyText(family)]),
|
||||
);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "trigIdentity": {
|
||||
const identity = identityMatching(topic.query);
|
||||
if (!identity) {
|
||||
return answer(
|
||||
"Not in the sheet",
|
||||
"Known identities: " + TRIG_IDENTITIES.map((entry) => entry.name).join(", "),
|
||||
);
|
||||
}
|
||||
return answer(identity.plain, `${identity.name}: ${identity.plain}`);
|
||||
}
|
||||
|
||||
case "digitSearch": {
|
||||
const outcome = findDigits(topic.pattern, topic.constant, topic.occurrence);
|
||||
switch (outcome.kind) {
|
||||
case "invalidPattern":
|
||||
return answer("Cannot search", outcome.reason);
|
||||
case "notFound": {
|
||||
// "Not in pi" and "not in the first 10,000 digits of pi" are very
|
||||
// different claims, and only the second one is true.
|
||||
let detail =
|
||||
`${topic.pattern} does not appear in the first ` +
|
||||
`${formatInt(outcome.searchedDigits)} digits of ${constantSpokenName(topic.constant)}.`;
|
||||
const expected = expectedFirstPosition(topic.pattern.length);
|
||||
if (expected !== null && expected > outcome.searchedDigits) {
|
||||
const article = [8, 11, 18].includes(topic.pattern.length) ? "An" : "A";
|
||||
detail +=
|
||||
` ${article} ${topic.pattern.length}-digit run turns up around the ` +
|
||||
`${formatInt(expected)}th place on average, so this needs a deeper expansion.`;
|
||||
}
|
||||
return {
|
||||
headline: `Not in the first ${formatInt(outcome.searchedDigits)} digits`,
|
||||
detail,
|
||||
fields: [],
|
||||
unresolvedWorkload: {
|
||||
kind: "digitSearch",
|
||||
constant: topic.constant,
|
||||
pattern: topic.pattern,
|
||||
occurrence: topic.occurrence,
|
||||
},
|
||||
};
|
||||
}
|
||||
case "found": {
|
||||
const match = outcome.match;
|
||||
const ordinalText = ordinalWord(topic.occurrence);
|
||||
const places =
|
||||
match.start === match.end ? `place ${match.start}` : `places ${match.start}–${match.end}`;
|
||||
return answer(
|
||||
`${constantDisplayName(topic.constant)}: ${places}`,
|
||||
`The ${ordinalText} appearance of ${topic.pattern} in ${constantSpokenName(topic.constant)} ` +
|
||||
`is at decimal ${places}, in …${highlightedMatch(match)}…`,
|
||||
[
|
||||
["Start", String(match.start)],
|
||||
["End", String(match.end)],
|
||||
["Context", highlightedMatch(match)],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "digitCount": {
|
||||
const counted = countDigitsIn(topic.pattern, topic.constant);
|
||||
return {
|
||||
headline: `${counted.occurrences} time${counted.occurrences === 1 ? "" : "s"}`,
|
||||
detail:
|
||||
`${topic.pattern} appears ${counted.occurrences} time${counted.occurrences === 1 ? "" : "s"} ` +
|
||||
`in the first ${formatInt(counted.searchedDigits)} digits of ${constantSpokenName(topic.constant)}.`,
|
||||
fields: [["Searched", `${formatInt(counted.searchedDigits)} digits`]],
|
||||
unresolvedWorkload: { kind: "digitCount", constant: topic.constant, pattern: topic.pattern },
|
||||
};
|
||||
}
|
||||
|
||||
case "digitsAt": {
|
||||
if (topic.to - topic.from >= 200) {
|
||||
return answer("Too many digits", "Ask for a span under 200 digits.");
|
||||
}
|
||||
const digits = digitsAt(topic.constant, topic.from, topic.to);
|
||||
if (!digits) {
|
||||
return {
|
||||
headline: "Out of range",
|
||||
detail:
|
||||
`That is past the ${formatInt(MAXIMUM_COMPUTED_DIGITS)} ` +
|
||||
`digits computed on device.`,
|
||||
fields: [],
|
||||
unresolvedWorkload: { kind: "constantDigits", constant: topic.constant, count: topic.to },
|
||||
};
|
||||
}
|
||||
return answer(
|
||||
digits,
|
||||
`Decimal places ${topic.from}–${topic.to} of ${constantSpokenName(topic.constant)} are ${digits}.`,
|
||||
[["Places", `${topic.from}–${topic.to}`]],
|
||||
);
|
||||
}
|
||||
|
||||
case "shapeArea": {
|
||||
const parts = shapeSummary(topic.shape);
|
||||
if (parts.length === 0) {
|
||||
return answer("Not enough measurements", "That shape needs more values.");
|
||||
}
|
||||
return answer(
|
||||
parts.map(([label, value]) => `${label} ${format(value)}`).join(", "),
|
||||
`For that ${shapeName(topic.shape)}: ` +
|
||||
parts.map(([label, value]) => `${label.toLowerCase()} ${format(value)}`).join(", ") +
|
||||
".",
|
||||
parts.map(([label, value]) => [label, format(value)]),
|
||||
);
|
||||
}
|
||||
|
||||
case "triangleFromSides": {
|
||||
const result = triangleFromSides(topic.a, topic.b, topic.c);
|
||||
switch (result.kind) {
|
||||
case "impossible":
|
||||
return answer("No such triangle", result.reason);
|
||||
case "one":
|
||||
case "two": {
|
||||
const triangle = result.kind === "one" ? result.triangle : result.first;
|
||||
const [angleA, angleB, angleC] = triangleAnglesInDegrees(triangle);
|
||||
return answer(
|
||||
`Area ${format(triangleArea(triangle))}, ${triangleKind(triangle)}`,
|
||||
`Angles ${format(angleA)}°, ${format(angleB)}°, ${format(angleC)}°; ` +
|
||||
`area ${format(triangleArea(triangle))}; perimeter ${format(trianglePerimeter(triangle))}.`,
|
||||
[
|
||||
["Angle A", `${format(angleA)}°`],
|
||||
["Angle B", `${format(angleB)}°`],
|
||||
["Angle C", `${format(angleC)}°`],
|
||||
["Area", format(triangleArea(triangle))],
|
||||
["Perimeter", format(trianglePerimeter(triangle))],
|
||||
["Type", triangleKind(triangle)],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "pythagoras": {
|
||||
const missing = pythagoras(topic.a, topic.b, topic.c);
|
||||
if (missing === null) {
|
||||
return answer(
|
||||
"Cannot solve",
|
||||
"Give two of the three sides, and a leg must be shorter than the hypotenuse.",
|
||||
);
|
||||
}
|
||||
return answer(format(missing), `The missing side is ${format(missing)}.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function answer(headline: string, detail: string, fields: [string, string][] = []): AdvancedAnswer {
|
||||
return { headline, detail, fields, unresolvedWorkload: null };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Extraction helpers
|
||||
|
||||
export function firstInt(text: string): number | null {
|
||||
return allInts(text)[0] ?? null;
|
||||
}
|
||||
|
||||
export function allInts(text: string): number[] {
|
||||
return (text.match(/-?\d+/g) ?? []).map(Number).filter(Number.isSafeInteger);
|
||||
}
|
||||
|
||||
export function allDoubles(text: string): number[] {
|
||||
return (text.match(/-?\d+(?:\.\d+)?/g) ?? []).map(Number).filter(Number.isFinite);
|
||||
}
|
||||
|
||||
export function lastDouble(text: string): number | null {
|
||||
const values = allDoubles(text);
|
||||
return values.length > 0 ? values[values.length - 1]! : null;
|
||||
}
|
||||
|
||||
function firstDoubleAfter(keywords: string[], text: string): number | null {
|
||||
for (const keyword of keywords) {
|
||||
const index = text.indexOf(keyword);
|
||||
if (index < 0) continue;
|
||||
const tail = text.slice(index + keyword.length);
|
||||
const value = allDoubles(tail)[0];
|
||||
if (value !== undefined) return value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** "from 0 to 5" */
|
||||
export function boundsIn(text: string): [number, number] | null {
|
||||
const match = text.match(/from\s+(-?[0-9.]+)\s+to\s+(-?[0-9.]+)/);
|
||||
if (!match) return null;
|
||||
const lower = Number(match[1]);
|
||||
const upper = Number(match[2]);
|
||||
if (!Number.isFinite(lower) || !Number.isFinite(upper)) return null;
|
||||
return [lower, upper];
|
||||
}
|
||||
|
||||
/** Take everything after the topic keyword and parse it as an expression. */
|
||||
function expressionTail(original: string, keywords: string[]): MathExpression | null {
|
||||
const lowered = original.toLowerCase();
|
||||
for (const keyword of [...keywords].sort((a, b) => b.length - a.length)) {
|
||||
const index = lowered.indexOf(keyword);
|
||||
if (index < 0) continue;
|
||||
let tail = original.slice(index + keyword.length);
|
||||
// Drop trailing clauses that belong to the command, not the maths.
|
||||
for (const terminator of [" from ", " as ", " with respect to ", " to order ", " dx"]) {
|
||||
const cut = tail.toLowerCase().indexOf(terminator);
|
||||
if (cut >= 0) tail = tail.slice(0, cut);
|
||||
}
|
||||
const trimmed = tail.replace(/^[ .,?]+|[ .,?]+$/g, "");
|
||||
if (!trimmed) continue;
|
||||
try {
|
||||
return parseSpoken(trimmed);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function format(value: number): string {
|
||||
return describeNumber(fromDecimal(value));
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
// Limits, Taylor series, and curve analysis.
|
||||
|
||||
import {
|
||||
type MathExpression,
|
||||
addExpr,
|
||||
divideExpr,
|
||||
multiplyExpr,
|
||||
num,
|
||||
numberValue,
|
||||
powerExpr,
|
||||
subtractExpr,
|
||||
variable as variableExpr,
|
||||
ONE,
|
||||
ZERO,
|
||||
} from "./expression";
|
||||
import { describeNumber, divide as divideNumber, fromDecimal, integer, isNegative, isOne, negated } from "./math-number";
|
||||
import { evaluateValue } from "./evaluator";
|
||||
import { differentiate } from "./derivative";
|
||||
import { simplify } from "./simplifier";
|
||||
import { Polynomial } from "./polynomial";
|
||||
import { numericRoots as polynomialNumericRoots } from "./solver";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Limits
|
||||
|
||||
export type LimitApproach = "both" | "fromLeft" | "fromRight";
|
||||
|
||||
export type LimitResult =
|
||||
| { kind: "value"; value: number }
|
||||
| { kind: "positiveInfinity" }
|
||||
| { kind: "negativeInfinity" }
|
||||
/** One-sided limits disagree, so the two-sided limit does not exist. */
|
||||
| { kind: "doesNotExist"; left: number | null; right: number | null }
|
||||
| { kind: "indeterminate" };
|
||||
|
||||
export function limitText(result: LimitResult): string {
|
||||
switch (result.kind) {
|
||||
case "value":
|
||||
return describeNumber(fromDecimal(result.value));
|
||||
case "positiveInfinity":
|
||||
return "+∞";
|
||||
case "negativeInfinity":
|
||||
return "−∞";
|
||||
case "doesNotExist":
|
||||
return "does not exist";
|
||||
case "indeterminate":
|
||||
return "indeterminate";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Limit of `expression` as `variable` → `point`.
|
||||
*
|
||||
* Direct substitution first, then L'Hôpital for 0/0 and ∞/∞, then a numeric
|
||||
* squeeze. The order matters: substitution is exact when it works, L'Hôpital
|
||||
* is exact when it applies, and only the leftovers get the approximate
|
||||
* treatment.
|
||||
*/
|
||||
export function limit(
|
||||
expression: MathExpression,
|
||||
variable: string,
|
||||
point: number,
|
||||
approach: LimitApproach = "both",
|
||||
): LimitResult {
|
||||
if (approach === "both" && Number.isFinite(point)) {
|
||||
const direct = evaluateValue(expression, { [variable]: point });
|
||||
if (direct !== null && Number.isFinite(direct)) {
|
||||
return { kind: "value", value: direct };
|
||||
}
|
||||
}
|
||||
const hospital = lHopital(expression, variable, point, 0);
|
||||
if (hospital) return hospital;
|
||||
return numericLimit(expression, variable, point, approach);
|
||||
}
|
||||
|
||||
/** Detect an indeterminate quotient and differentiate top and bottom. */
|
||||
function lHopital(
|
||||
expression: MathExpression,
|
||||
variable: string,
|
||||
point: number,
|
||||
depth: number,
|
||||
): LimitResult | null {
|
||||
// Bounded: a quotient that stays indeterminate forever (sin(1/x)/x) must
|
||||
// give up rather than recurse without end.
|
||||
if (depth >= 8 || !Number.isFinite(point)) return null;
|
||||
const quotient = asQuotient(expression);
|
||||
if (!quotient) return null;
|
||||
const [numerator, denominator] = quotient;
|
||||
|
||||
const top = evaluateValue(numerator, { [variable]: point });
|
||||
const bottom = evaluateValue(denominator, { [variable]: point });
|
||||
if (top === null || bottom === null) return null;
|
||||
|
||||
const isZeroOverZero = Math.abs(top) < 1e-12 && Math.abs(bottom) < 1e-12;
|
||||
const isInfinityOverInfinity = !Number.isFinite(top) && !Number.isFinite(bottom);
|
||||
if (!isZeroOverZero && !isInfinityOverInfinity) return null;
|
||||
|
||||
const dTop = differentiate(numerator, variable);
|
||||
const dBottom = differentiate(denominator, variable);
|
||||
// A vanishing derivative of the denominator means the rule does not apply
|
||||
// again; fall through to the numeric path.
|
||||
const bottomValue = evaluateValue(dBottom, { [variable]: point });
|
||||
if (bottomValue === null || !Number.isFinite(bottomValue)) return null;
|
||||
|
||||
if (Math.abs(bottomValue) > 1e-12) {
|
||||
const topValue = evaluateValue(dTop, { [variable]: point });
|
||||
if (topValue !== null && Number.isFinite(topValue)) {
|
||||
return { kind: "value", value: topValue / bottomValue };
|
||||
}
|
||||
}
|
||||
return lHopital(divideExpr(dTop, dBottom), variable, point, depth + 1);
|
||||
}
|
||||
|
||||
/** Recognise `a / b`, which the tree stores as `a · b^-1`. */
|
||||
export function asQuotient(expression: MathExpression): [MathExpression, MathExpression] | null {
|
||||
if (expression.type !== "multiply") return null;
|
||||
const numerator: MathExpression[] = [];
|
||||
const denominator: MathExpression[] = [];
|
||||
for (const factor of expression.factors) {
|
||||
if (factor.type === "power") {
|
||||
const power = numberValue(factor.exponent);
|
||||
if (power && isNegative(power)) {
|
||||
const positive = negated(power);
|
||||
denominator.push(isOne(positive) ? factor.base : powerExpr(factor.base, num(positive)));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
numerator.push(factor);
|
||||
}
|
||||
if (denominator.length === 0) return null;
|
||||
return [
|
||||
numerator.length === 0 ? ONE : numerator.length === 1 ? numerator[0]! : multiplyExpr(numerator),
|
||||
denominator.length === 1 ? denominator[0]! : multiplyExpr(denominator),
|
||||
];
|
||||
}
|
||||
|
||||
function numericLimit(
|
||||
expression: MathExpression,
|
||||
variable: string,
|
||||
point: number,
|
||||
approach: LimitApproach,
|
||||
): LimitResult {
|
||||
const sampleSide = (side: LimitApproach): number | null => {
|
||||
if (!Number.isFinite(point)) {
|
||||
// At infinity, march outward instead of shrinking a step.
|
||||
const sign = point > 0 ? 1 : -1;
|
||||
let last: number | null = null;
|
||||
for (const magnitude of [1e3, 1e4, 1e5, 1e6, 1e7]) {
|
||||
const value = evaluateValue(expression, { [variable]: sign * magnitude });
|
||||
if (value === null || !Number.isFinite(value)) return last;
|
||||
last = value;
|
||||
}
|
||||
return last;
|
||||
}
|
||||
const samples: number[] = [];
|
||||
for (const step of [1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7]) {
|
||||
const offset = side === "fromLeft" ? -step : step;
|
||||
const value = evaluateValue(expression, { [variable]: point + offset });
|
||||
if (value === null || !Number.isFinite(value)) continue;
|
||||
samples.push(value);
|
||||
}
|
||||
const last = samples[samples.length - 1];
|
||||
if (last === undefined) return null;
|
||||
// Divergence is a TREND, not a threshold. 1/x reaches only 1e7 at the
|
||||
// smallest step sampled here, so a fixed "> 1e12" cutoff calls it finite;
|
||||
// magnitudes growing by an order per step do not.
|
||||
if (samples.length >= 3) {
|
||||
const tail = samples.slice(-3);
|
||||
const magnitudes = tail.map((value) => Math.abs(value));
|
||||
const growing = magnitudes.every(
|
||||
(value, index) => index === 0 || value > magnitudes[index - 1]! * 5,
|
||||
);
|
||||
if (growing && (magnitudes[magnitudes.length - 1] ?? 0) > 1e4) {
|
||||
return last > 0 ? Infinity : -Infinity;
|
||||
}
|
||||
}
|
||||
return last;
|
||||
};
|
||||
|
||||
switch (approach) {
|
||||
case "fromLeft": {
|
||||
const value = sampleSide("fromLeft");
|
||||
return value === null ? { kind: "indeterminate" } : classify(value);
|
||||
}
|
||||
case "fromRight": {
|
||||
const value = sampleSide("fromRight");
|
||||
return value === null ? { kind: "indeterminate" } : classify(value);
|
||||
}
|
||||
case "both": {
|
||||
const left = sampleSide("fromLeft");
|
||||
const right = sampleSide("fromRight");
|
||||
if (left === null || right === null) return { kind: "indeterminate" };
|
||||
// Scale-relative comparison: two values near 1e6 differing by 1 are the
|
||||
// same limit; two near 0 differing by 1 are not.
|
||||
const scale = Math.max(Math.abs(left), Math.abs(right), 1);
|
||||
if (Math.abs(left - right) >= 1e-4 * scale) {
|
||||
return { kind: "doesNotExist", left, right };
|
||||
}
|
||||
return classify((left + right) / 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function classify(value: number): LimitResult {
|
||||
if (!Number.isFinite(value)) {
|
||||
return value > 0 ? { kind: "positiveInfinity" } : { kind: "negativeInfinity" };
|
||||
}
|
||||
if (value > 1e12) return { kind: "positiveInfinity" };
|
||||
if (value < -1e12) return { kind: "negativeInfinity" };
|
||||
return { kind: "value", value };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Series
|
||||
|
||||
/** Taylor expansion about `centre`, to `order` terms. */
|
||||
export function taylor(
|
||||
expression: MathExpression,
|
||||
variable: string,
|
||||
order = 5,
|
||||
centre = 0,
|
||||
): MathExpression | null {
|
||||
if (order < 0 || order > 12) return null;
|
||||
const terms: MathExpression[] = [];
|
||||
let derivative = expression;
|
||||
let factorial = 1;
|
||||
|
||||
for (let degree = 0; degree <= order; degree++) {
|
||||
if (degree > 0) {
|
||||
derivative = differentiate(derivative, variable);
|
||||
factorial *= degree;
|
||||
}
|
||||
const coefficient = evaluateValue(derivative, { [variable]: centre });
|
||||
if (coefficient === null || !Number.isFinite(coefficient)) return null;
|
||||
if (Math.abs(coefficient) <= 1e-12) continue;
|
||||
|
||||
const scaled = divideNumber(fromDecimal(coefficient), integer(factorial));
|
||||
const shifted: MathExpression =
|
||||
centre === 0
|
||||
? variableExpr(variable)
|
||||
: subtractExpr(variableExpr(variable), num(fromDecimal(centre)));
|
||||
const power: MathExpression =
|
||||
degree === 0 ? ONE : degree === 1 ? shifted : powerExpr(shifted, num(integer(degree)));
|
||||
terms.push(degree === 0 ? num(scaled) : multiplyExpr([num(scaled), power]));
|
||||
}
|
||||
if (terms.length === 0) return ZERO;
|
||||
return simplify(addExpr(terms));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Curve analysis
|
||||
|
||||
export type CriticalPointKind = "minimum" | "maximum" | "inflection" | "undetermined";
|
||||
|
||||
export type CriticalPoint = {
|
||||
x: number;
|
||||
y: number;
|
||||
kind: CriticalPointKind;
|
||||
};
|
||||
|
||||
export function criticalPointText(point: CriticalPoint): string {
|
||||
const xText = describeNumber(fromDecimal(point.x));
|
||||
const yText = describeNumber(fromDecimal(point.y));
|
||||
return `${point.kind} at (${xText}, ${yText})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Critical points classified by the second derivative, falling back to a
|
||||
* sign test where the second derivative vanishes.
|
||||
*/
|
||||
export function criticalPoints(
|
||||
expression: MathExpression,
|
||||
variable: string,
|
||||
range: [number, number] = [-50, 50],
|
||||
): CriticalPoint[] {
|
||||
const first = differentiate(expression, variable);
|
||||
const second = differentiate(first, variable);
|
||||
|
||||
let roots: number[];
|
||||
const polynomial = Polynomial.extract(first, variable);
|
||||
if (polynomial) {
|
||||
roots = polynomialNumericRoots(polynomial, range, 20_000);
|
||||
} else {
|
||||
roots = numericRootsOfExpression(first, variable, range);
|
||||
}
|
||||
|
||||
const points: CriticalPoint[] = [];
|
||||
for (const x of roots) {
|
||||
const y = evaluateValue(expression, { [variable]: x });
|
||||
if (y === null || !Number.isFinite(y)) continue;
|
||||
const curvature = evaluateValue(second, { [variable]: x }) ?? 0;
|
||||
let kind: CriticalPointKind;
|
||||
if (curvature > 1e-9) {
|
||||
kind = "minimum";
|
||||
} else if (curvature < -1e-9) {
|
||||
kind = "maximum";
|
||||
} else {
|
||||
// Second-derivative test is inconclusive; look at how the first
|
||||
// derivative behaves either side.
|
||||
const left = evaluateValue(first, { [variable]: x - 1e-4 }) ?? 0;
|
||||
const right = evaluateValue(first, { [variable]: x + 1e-4 }) ?? 0;
|
||||
if (left < 0 && right > 0) kind = "minimum";
|
||||
else if (left > 0 && right < 0) kind = "maximum";
|
||||
else kind = "inflection";
|
||||
}
|
||||
points.push({ x, y, kind });
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
export function numericRootsOfExpression(
|
||||
expression: MathExpression,
|
||||
variable: string,
|
||||
range: [number, number],
|
||||
samples = 20_000,
|
||||
): number[] {
|
||||
const [lower, upper] = range;
|
||||
const roots: number[] = [];
|
||||
const step = (upper - lower) / samples;
|
||||
let previousX = lower;
|
||||
let previousY = evaluateValue(expression, { [variable]: previousX });
|
||||
|
||||
for (let index = 1; index <= samples; index++) {
|
||||
const x = lower + index * step;
|
||||
const y = evaluateValue(expression, { [variable]: x });
|
||||
const lastX = previousX;
|
||||
const lastY = previousY;
|
||||
previousX = x;
|
||||
previousY = y;
|
||||
if (y === null || lastY === null) continue;
|
||||
if (Math.sign(lastY) === Math.sign(y)) continue;
|
||||
if (Math.abs(y) >= 1e6 || Math.abs(lastY) >= 1e6) continue;
|
||||
|
||||
let low = lastX;
|
||||
let high = x;
|
||||
for (let iteration = 0; iteration < 60; iteration++) {
|
||||
const mid = (low + high) / 2;
|
||||
const value = evaluateValue(expression, { [variable]: mid });
|
||||
const lowValue = evaluateValue(expression, { [variable]: low });
|
||||
if (value === null || lowValue === null) break;
|
||||
if (value === 0) {
|
||||
low = mid;
|
||||
high = mid;
|
||||
break;
|
||||
}
|
||||
if (Math.sign(value) === Math.sign(lowValue)) {
|
||||
low = mid;
|
||||
} else {
|
||||
high = mid;
|
||||
}
|
||||
}
|
||||
const root = (low + high) / 2;
|
||||
// Same pole guard as the main solver: verify the residual.
|
||||
const residual = evaluateValue(expression, { [variable]: root });
|
||||
if (residual === null || Math.abs(residual) >= 1e-6) continue;
|
||||
if (!roots.some((existing) => Math.abs(existing - root) < 1e-6)) roots.push(root);
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
@@ -0,0 +1,591 @@
|
||||
// Digit expansions of the well-known constants, computed exactly. Computed
|
||||
// rather than tabulated: a hardcoded string of π is a thing nobody can check,
|
||||
// and a single transposed digit would silently shift every position this
|
||||
// feature reports. Everything here comes out of integer arithmetic that can
|
||||
// be re-derived and tested.
|
||||
//
|
||||
// JavaScript's native BigInt supplies the operation set the generators need
|
||||
// (add, subtract, compare, multiply/divide by a small scalar).
|
||||
// The deep paths are async and yield to the event loop periodically — a
|
||||
// multi-minute synchronous grind would freeze the app's whole UI thread.
|
||||
|
||||
export type MathConstantName = "pi" | "e" | "phi" | "sqrt2" | "sqrt3" | "sqrt5";
|
||||
|
||||
export const ALL_CONSTANT_NAMES: readonly MathConstantName[] = ["pi", "e", "phi", "sqrt2", "sqrt3", "sqrt5"];
|
||||
|
||||
export function constantDisplayName(constant: MathConstantName): string {
|
||||
switch (constant) {
|
||||
case "pi":
|
||||
return "π";
|
||||
case "e":
|
||||
return "e";
|
||||
case "phi":
|
||||
return "φ";
|
||||
case "sqrt2":
|
||||
return "√2";
|
||||
case "sqrt3":
|
||||
return "√3";
|
||||
case "sqrt5":
|
||||
return "√5";
|
||||
}
|
||||
}
|
||||
|
||||
export function constantSpokenName(constant: MathConstantName): string {
|
||||
switch (constant) {
|
||||
case "pi":
|
||||
return "pi";
|
||||
case "e":
|
||||
return "e";
|
||||
case "phi":
|
||||
return "the golden ratio";
|
||||
case "sqrt2":
|
||||
return "the square root of 2";
|
||||
case "sqrt3":
|
||||
return "the square root of 3";
|
||||
case "sqrt5":
|
||||
return "the square root of 5";
|
||||
}
|
||||
}
|
||||
|
||||
/** Digits before the decimal point — 1 for all of these. */
|
||||
export const CONSTANT_INTEGER_PART_DIGITS = 1;
|
||||
|
||||
export function constantNamed(text: string): MathConstantName | null {
|
||||
const lowered = text.toLowerCase();
|
||||
if (lowered.includes("golden") || lowered.includes("phi")) return "phi";
|
||||
if (lowered.includes("root of 2") || lowered.includes("root two") || lowered.includes("sqrt2")) {
|
||||
return "sqrt2";
|
||||
}
|
||||
if (lowered.includes("root of 3") || lowered.includes("root three")) return "sqrt3";
|
||||
if (lowered.includes("root of 5") || lowered.includes("root five")) return "sqrt5";
|
||||
// Word-boundary matched, not substring: `includes("pi")` also fires on
|
||||
// "pie", "spin", and "copying", and `=== "e"` only ever matched a
|
||||
// single-character utterance, so "the digits of e" never resolved.
|
||||
if (lowered.includes("π") || hasWord("pi", lowered)) return "pi";
|
||||
if (hasWord("e", lowered) || lowered.includes("euler")) return "e";
|
||||
return null;
|
||||
}
|
||||
|
||||
function hasWord(word: string, text: string): boolean {
|
||||
return new RegExp(`\\b${word}\\b`).test(text);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cancellation and progress
|
||||
|
||||
/** Cooperative cancellation for the long paths. */
|
||||
export type ComputeCancellation = () => boolean;
|
||||
|
||||
export const NEVER_CANCELLED: ComputeCancellation = () => false;
|
||||
|
||||
/** Raised when a long run is cancelled partway. */
|
||||
export class ComputeCancelled extends Error {
|
||||
constructor() {
|
||||
super("Cancelled");
|
||||
this.name = "ComputeCancelled";
|
||||
}
|
||||
}
|
||||
|
||||
export type ComputeProgress = (fraction: number, stage: string) => void;
|
||||
|
||||
// setTimeout via globalThis so this module needs no platform lib: it runs
|
||||
// under NativeScript's globals in the app and under Node in the tests.
|
||||
const scheduleMacrotask: (callback: () => void) => void = (callback) =>
|
||||
(globalThis as unknown as { setTimeout: (fn: () => void, ms: number) => unknown }).setTimeout(callback, 0);
|
||||
|
||||
/**
|
||||
* Yield to the event loop when the current slice has run long enough. The
|
||||
* generators call this between series terms so a deep run stays cancellable
|
||||
* and the rest of the app keeps painting.
|
||||
*/
|
||||
class Yielder {
|
||||
private lastYieldAt = Date.now();
|
||||
|
||||
async maybeYield(): Promise<void> {
|
||||
if (Date.now() - this.lastYieldAt < 50) return;
|
||||
await new Promise<void>((resolve) => scheduleMacrotask(resolve));
|
||||
this.lastYieldAt = Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Limits
|
||||
|
||||
/**
|
||||
* How far the on-device generator will go for an ordinary question.
|
||||
*
|
||||
* Machin's formula is O(n²) in the digit count with scalar-only big
|
||||
* arithmetic. 10,000 digits is well under a second and finds any two- or
|
||||
* three-digit run plus most four-digit ones; past this, the wearer opts into
|
||||
* a long run explicitly.
|
||||
*/
|
||||
export const MAXIMUM_COMPUTED_DIGITS = 10_000;
|
||||
|
||||
/**
|
||||
* The furthest an opted-in long run will go, however much time the wearer
|
||||
* offers. Not a time limit — the caller has already accepted the wait — but
|
||||
* a memory-and-honesty one: the O(n²) cost puts this at hours on a phone,
|
||||
* past which nobody is still waiting.
|
||||
*/
|
||||
export const MAXIMUM_FEASIBLE_DIGITS = 2_000_000;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cache
|
||||
|
||||
/**
|
||||
* The same constant is asked for repeatedly within one session (search, then
|
||||
* context, then a second search), and recomputing 10,000 digits each time
|
||||
* would be pointlessly slow. Grow-only.
|
||||
*/
|
||||
const cache = new Map<MathConstantName, string>();
|
||||
|
||||
function cachedDigits(constant: MathConstantName, atLeast: number): string | null {
|
||||
const cached = cache.get(constant);
|
||||
if (!cached || cached.length < atLeast) return null;
|
||||
return cached;
|
||||
}
|
||||
|
||||
function storeDigits(constant: MathConstantName, digits: string): void {
|
||||
const existing = cache.get(constant);
|
||||
if (existing && existing.length >= digits.length) return;
|
||||
cache.set(constant, digits);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public entry points
|
||||
|
||||
/**
|
||||
* Fractional digits only — the part after the decimal point, which is what
|
||||
* "position N of π" universally means. Clamped to MAXIMUM_COMPUTED_DIGITS;
|
||||
* the deeper run is a separate call the wearer has to opt into, so no
|
||||
* ordinary caller can accidentally block the app for minutes.
|
||||
*/
|
||||
export function fractionalDigits(constant: MathConstantName, count: number): string | null {
|
||||
const requested = Math.min(Math.max(count, 1), MAXIMUM_COMPUTED_DIGITS);
|
||||
const cached = cachedDigits(constant, requested);
|
||||
if (cached) return cached.slice(0, requested);
|
||||
// The shallow path runs synchronously; at 10k digits it is fast enough that
|
||||
// an async hop would only complicate every caller.
|
||||
const digits = computeSync(constant, requested);
|
||||
if (digits === null) return null;
|
||||
storeDigits(constant, digits);
|
||||
return digits.slice(0, requested);
|
||||
}
|
||||
|
||||
/**
|
||||
* The opted-in deep run. Cancellable, and reports progress, because a
|
||||
* multi-minute grind with no way out and nothing on screen is
|
||||
* indistinguishable from a hang.
|
||||
*/
|
||||
export async function deepFractionalDigits(
|
||||
constant: MathConstantName,
|
||||
count: number,
|
||||
cancellation: ComputeCancellation = NEVER_CANCELLED,
|
||||
progress: ComputeProgress | null = null,
|
||||
): Promise<string | null> {
|
||||
const requested = Math.min(Math.max(count, 1), MAXIMUM_FEASIBLE_DIGITS);
|
||||
const cached = cachedDigits(constant, requested);
|
||||
if (cached) return cached.slice(0, requested);
|
||||
const digits = await compute(constant, requested, cancellation, progress, new Yielder());
|
||||
if (digits === null) return null;
|
||||
storeDigits(constant, digits);
|
||||
return digits.slice(0, requested);
|
||||
}
|
||||
|
||||
function computeSync(constant: MathConstantName, requested: number): string | null {
|
||||
// A resolved-synchronously wrapper would still be async; instead run the
|
||||
// shared generator with a yielder that never fires (50ms slices cannot
|
||||
// elapse mid-loop when the whole computation is sub-second) by executing
|
||||
// the promise eagerly. The generators only await through Yielder.maybeYield,
|
||||
// which resolves immediately below the time threshold, so the promise
|
||||
// settles synchronously enough — but rather than rely on that, the shallow
|
||||
// path uses the dedicated synchronous variants.
|
||||
return computeCore(constant, requested, NEVER_CANCELLED, null, null);
|
||||
}
|
||||
|
||||
async function compute(
|
||||
constant: MathConstantName,
|
||||
requested: number,
|
||||
cancellation: ComputeCancellation,
|
||||
progress: ComputeProgress | null,
|
||||
yielder: Yielder,
|
||||
): Promise<string | null> {
|
||||
return computeCoreAsync(constant, requested, cancellation, progress, yielder);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Core generators
|
||||
//
|
||||
// Each exists in a synchronous and an asynchronous variant sharing the same
|
||||
// arithmetic. The async ones interleave event-loop yields; the sync ones are
|
||||
// used only under MAXIMUM_COMPUTED_DIGITS where the total cost is small.
|
||||
|
||||
/**
|
||||
* Guard digits absorb the truncation error the series accumulates in its
|
||||
* least significant places; without them the last handful of reported digits
|
||||
* are wrong, which for a position-reporting feature is the whole ballgame.
|
||||
*/
|
||||
const GUARD_DIGITS = 20;
|
||||
|
||||
function computeCore(
|
||||
constant: MathConstantName,
|
||||
requested: number,
|
||||
cancellation: ComputeCancellation,
|
||||
progress: ComputeProgress | null,
|
||||
_yielder: null,
|
||||
): string | null {
|
||||
const scale = requested + GUARD_DIGITS;
|
||||
let scaled: bigint;
|
||||
switch (constant) {
|
||||
case "pi":
|
||||
scaled = machinPiSync(scale, cancellation, progress);
|
||||
break;
|
||||
case "e":
|
||||
scaled = eulerESync(scale, cancellation, progress);
|
||||
break;
|
||||
case "phi": {
|
||||
// φ = (1 + √5) / 2
|
||||
const root = integerSquareRootSync(5, scale, cancellation, progress);
|
||||
scaled = (root + powerOfTen(scale)) / 2n;
|
||||
break;
|
||||
}
|
||||
case "sqrt2":
|
||||
scaled = integerSquareRootSync(2, scale, cancellation, progress);
|
||||
break;
|
||||
case "sqrt3":
|
||||
scaled = integerSquareRootSync(3, scale, cancellation, progress);
|
||||
break;
|
||||
case "sqrt5":
|
||||
scaled = integerSquareRootSync(5, scale, cancellation, progress);
|
||||
break;
|
||||
}
|
||||
return finishDigits(scaled, requested);
|
||||
}
|
||||
|
||||
async function computeCoreAsync(
|
||||
constant: MathConstantName,
|
||||
requested: number,
|
||||
cancellation: ComputeCancellation,
|
||||
progress: ComputeProgress | null,
|
||||
yielder: Yielder,
|
||||
): Promise<string | null> {
|
||||
const scale = requested + GUARD_DIGITS;
|
||||
let scaled: bigint;
|
||||
switch (constant) {
|
||||
case "pi":
|
||||
scaled = await machinPi(scale, cancellation, progress, yielder);
|
||||
break;
|
||||
case "e":
|
||||
scaled = await eulerE(scale, cancellation, progress, yielder);
|
||||
break;
|
||||
case "phi": {
|
||||
const root = await integerSquareRoot(5, scale, cancellation, progress, yielder);
|
||||
scaled = (root + powerOfTen(scale)) / 2n;
|
||||
break;
|
||||
}
|
||||
case "sqrt2":
|
||||
scaled = await integerSquareRoot(2, scale, cancellation, progress, yielder);
|
||||
break;
|
||||
case "sqrt3":
|
||||
scaled = await integerSquareRoot(3, scale, cancellation, progress, yielder);
|
||||
break;
|
||||
case "sqrt5":
|
||||
scaled = await integerSquareRoot(5, scale, cancellation, progress, yielder);
|
||||
break;
|
||||
}
|
||||
return finishDigits(scaled, requested);
|
||||
}
|
||||
|
||||
/**
|
||||
* The value is the constant × 10^scale. Strip the integer part, then the
|
||||
* guard digits.
|
||||
*/
|
||||
function finishDigits(scaled: bigint, requested: number): string | null {
|
||||
const text = scaled.toString();
|
||||
if (text.length <= CONSTANT_INTEGER_PART_DIGITS) return null;
|
||||
const fractional = text.slice(CONSTANT_INTEGER_PART_DIGITS);
|
||||
if (fractional.length < requested) return null;
|
||||
const trimmed = fractional.slice(0, fractional.length - GUARD_DIGITS);
|
||||
return trimmed.slice(0, requested);
|
||||
}
|
||||
|
||||
export function powerOfTen(exponent: number): bigint {
|
||||
return 10n ** BigInt(Math.max(0, exponent));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// π — Machin's formula: π = 16·arctan(1/5) − 4·arctan(1/239).
|
||||
//
|
||||
// Chosen over Chudnovsky because it needs only scalar big-integer operations
|
||||
// — no big×big multiply, no big÷big division, no square roots of big values.
|
||||
|
||||
// arctan(1/5) needs log10(239)/log10(5) ≈ 3.4× as many terms as arctan(1/239)
|
||||
// at the same scale, and each term costs the same, so the first phase is
|
||||
// ~77% of the work. Splitting the reported fraction that way keeps the
|
||||
// progress bar honest instead of stalling at half.
|
||||
const MACHIN_FIRST_SHARE = 0.77;
|
||||
|
||||
function machinPiSync(
|
||||
scale: number,
|
||||
cancellation: ComputeCancellation,
|
||||
progress: ComputeProgress | null,
|
||||
): bigint {
|
||||
const first =
|
||||
arctanReciprocalSync(5, scale, cancellation, (fraction) =>
|
||||
progress?.(fraction * MACHIN_FIRST_SHARE, "π series 1 of 2"),
|
||||
) * 16n;
|
||||
const second =
|
||||
arctanReciprocalSync(239, scale, cancellation, (fraction) =>
|
||||
progress?.(MACHIN_FIRST_SHARE + fraction * (1 - MACHIN_FIRST_SHARE), "π series 2 of 2"),
|
||||
) * 4n;
|
||||
return first - second;
|
||||
}
|
||||
|
||||
async function machinPi(
|
||||
scale: number,
|
||||
cancellation: ComputeCancellation,
|
||||
progress: ComputeProgress | null,
|
||||
yielder: Yielder,
|
||||
): Promise<bigint> {
|
||||
const first =
|
||||
(await arctanReciprocal(
|
||||
5,
|
||||
scale,
|
||||
cancellation,
|
||||
(fraction) => progress?.(fraction * MACHIN_FIRST_SHARE, "π series 1 of 2"),
|
||||
yielder,
|
||||
)) * 16n;
|
||||
const second =
|
||||
(await arctanReciprocal(
|
||||
239,
|
||||
scale,
|
||||
cancellation,
|
||||
(fraction) => progress?.(MACHIN_FIRST_SHARE + fraction * (1 - MACHIN_FIRST_SHARE), "π series 2 of 2"),
|
||||
yielder,
|
||||
)) * 4n;
|
||||
return first - second;
|
||||
}
|
||||
|
||||
/** arctan(1/x), scaled by 10^scale, by its alternating Taylor series. */
|
||||
function arctanReciprocalSync(
|
||||
x: number,
|
||||
scale: number,
|
||||
cancellation: ComputeCancellation,
|
||||
progress: ((fraction: number) => void) | null,
|
||||
): bigint {
|
||||
const bigX = BigInt(x);
|
||||
const xSquared = bigX * bigX;
|
||||
let power = powerOfTen(scale) / bigX;
|
||||
let sum = power;
|
||||
let divisor = 3n;
|
||||
let subtractNext = true;
|
||||
|
||||
// Terms shrink by a factor of x² each step, so the series dies after about
|
||||
// scale / (2·log10 x) of them. Known up front, which is what makes a real
|
||||
// fraction possible rather than a spinner.
|
||||
const expectedTerms = Math.max(1, scale / (2 * Math.log10(x)));
|
||||
let iterations = 0;
|
||||
|
||||
while (power !== 0n) {
|
||||
// Checked every term: one closure call is nothing beside a big-integer
|
||||
// division, and the alternative is an uncancellable multi-minute loop.
|
||||
if (cancellation()) throw new ComputeCancelled();
|
||||
|
||||
power /= xSquared;
|
||||
const term = power / divisor;
|
||||
if (term === 0n) break;
|
||||
sum = subtractNext ? sum - term : sum + term;
|
||||
subtractNext = !subtractNext;
|
||||
divisor += 2n;
|
||||
|
||||
iterations += 1;
|
||||
// Throttled: a million progress callbacks would cost more than the
|
||||
// arithmetic they are reporting on.
|
||||
if (progress && iterations % 256 === 0) {
|
||||
progress(Math.min(1, iterations / expectedTerms));
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
async function arctanReciprocal(
|
||||
x: number,
|
||||
scale: number,
|
||||
cancellation: ComputeCancellation,
|
||||
progress: ((fraction: number) => void) | null,
|
||||
yielder: Yielder,
|
||||
): Promise<bigint> {
|
||||
const bigX = BigInt(x);
|
||||
const xSquared = bigX * bigX;
|
||||
let power = powerOfTen(scale) / bigX;
|
||||
let sum = power;
|
||||
let divisor = 3n;
|
||||
let subtractNext = true;
|
||||
|
||||
const expectedTerms = Math.max(1, scale / (2 * Math.log10(x)));
|
||||
let iterations = 0;
|
||||
|
||||
while (power !== 0n) {
|
||||
if (cancellation()) throw new ComputeCancelled();
|
||||
|
||||
power /= xSquared;
|
||||
const term = power / divisor;
|
||||
if (term === 0n) break;
|
||||
sum = subtractNext ? sum - term : sum + term;
|
||||
subtractNext = !subtractNext;
|
||||
divisor += 2n;
|
||||
|
||||
iterations += 1;
|
||||
if (progress && iterations % 256 === 0) {
|
||||
progress(Math.min(1, iterations / expectedTerms));
|
||||
}
|
||||
if (iterations % 64 === 0) await yielder.maybeYield();
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// e = Σ 1/k!, scaled. Each term is the previous divided by k, so the whole
|
||||
// series needs only scalar division.
|
||||
|
||||
function eulerESync(
|
||||
scale: number,
|
||||
cancellation: ComputeCancellation,
|
||||
progress: ComputeProgress | null,
|
||||
): bigint {
|
||||
let term = powerOfTen(scale);
|
||||
let sum = term;
|
||||
let k = 1n;
|
||||
// The term loses log10(k) digits each step; the series ends when the
|
||||
// accumulated loss passes `scale`. Tracking that sum gives a fraction
|
||||
// without needing Stirling's approximation.
|
||||
let digitsShed = 0;
|
||||
let iterations = 0;
|
||||
|
||||
while (term !== 0n) {
|
||||
if (cancellation()) throw new ComputeCancelled();
|
||||
term /= k;
|
||||
sum += term;
|
||||
digitsShed += Math.log10(Number(k));
|
||||
k += 1n;
|
||||
iterations += 1;
|
||||
if (progress && iterations % 256 === 0) {
|
||||
progress(Math.min(1, digitsShed / Math.max(scale, 1)), "e series");
|
||||
}
|
||||
// 10^scale / k! underflows long before this, but a runaway loop is not an
|
||||
// acceptable failure mode.
|
||||
if (k > 1_000_000n) break;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
async function eulerE(
|
||||
scale: number,
|
||||
cancellation: ComputeCancellation,
|
||||
progress: ComputeProgress | null,
|
||||
yielder: Yielder,
|
||||
): Promise<bigint> {
|
||||
let term = powerOfTen(scale);
|
||||
let sum = term;
|
||||
let k = 1n;
|
||||
let digitsShed = 0;
|
||||
let iterations = 0;
|
||||
|
||||
while (term !== 0n) {
|
||||
if (cancellation()) throw new ComputeCancelled();
|
||||
term /= k;
|
||||
sum += term;
|
||||
digitsShed += Math.log10(Number(k));
|
||||
k += 1n;
|
||||
iterations += 1;
|
||||
if (progress && iterations % 256 === 0) {
|
||||
progress(Math.min(1, digitsShed / Math.max(scale, 1)), "e series");
|
||||
}
|
||||
if (iterations % 64 === 0) await yielder.maybeYield();
|
||||
if (k > 1_000_000n) break;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Square roots — ⌊√(value · 10^(2·scale))⌋, i.e. √value scaled by 10^scale.
|
||||
//
|
||||
// Digit-by-digit ("long division") extraction, which needs only add,
|
||||
// subtract, compare, and multiply-by-scalar.
|
||||
|
||||
function integerSquareRootSync(
|
||||
value: number,
|
||||
scale: number,
|
||||
cancellation: ComputeCancellation,
|
||||
progress: ComputeProgress | null,
|
||||
): bigint {
|
||||
// Work in pairs of decimal digits, which is what the algorithm consumes.
|
||||
const totalPairs = scale + 1;
|
||||
let remainder = 0n;
|
||||
let root = 0n;
|
||||
|
||||
for (let pairIndex = 0; pairIndex < totalPairs; pairIndex++) {
|
||||
if (cancellation()) throw new ComputeCancelled();
|
||||
if (progress && pairIndex % 256 === 0) {
|
||||
progress(pairIndex / totalPairs, "root extraction");
|
||||
}
|
||||
// Bring down the next two digits: the first pair is the integer part,
|
||||
// every later pair is zero because the radicand's fractional expansion is
|
||||
// all zeros.
|
||||
const bringDown = pairIndex === 0 ? BigInt(value) : 0n;
|
||||
remainder = remainder * 100n + bringDown;
|
||||
|
||||
// Find the largest d in 0...9 with (20·root + d)·d ≤ remainder.
|
||||
const twentyRoot = root * 20n;
|
||||
let chosen = 0n;
|
||||
let chosenProduct = 0n;
|
||||
for (let digit = 9n; digit >= 1n; digit--) {
|
||||
const candidate = (twentyRoot + digit) * digit;
|
||||
if (candidate <= remainder) {
|
||||
chosen = digit;
|
||||
chosenProduct = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
remainder -= chosenProduct;
|
||||
root = root * 10n + chosen;
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
async function integerSquareRoot(
|
||||
value: number,
|
||||
scale: number,
|
||||
cancellation: ComputeCancellation,
|
||||
progress: ComputeProgress | null,
|
||||
yielder: Yielder,
|
||||
): Promise<bigint> {
|
||||
const totalPairs = scale + 1;
|
||||
let remainder = 0n;
|
||||
let root = 0n;
|
||||
|
||||
for (let pairIndex = 0; pairIndex < totalPairs; pairIndex++) {
|
||||
if (cancellation()) throw new ComputeCancelled();
|
||||
if (progress && pairIndex % 256 === 0) {
|
||||
progress(pairIndex / totalPairs, "root extraction");
|
||||
}
|
||||
const bringDown = pairIndex === 0 ? BigInt(value) : 0n;
|
||||
remainder = remainder * 100n + bringDown;
|
||||
|
||||
const twentyRoot = root * 20n;
|
||||
let chosen = 0n;
|
||||
let chosenProduct = 0n;
|
||||
for (let digit = 9n; digit >= 1n; digit--) {
|
||||
const candidate = (twentyRoot + digit) * digit;
|
||||
if (candidate <= remainder) {
|
||||
chosen = digit;
|
||||
chosenProduct = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
remainder -= chosenProduct;
|
||||
root = root * 10n + chosen;
|
||||
if (pairIndex % 64 === 0) await yielder.maybeYield();
|
||||
}
|
||||
return root;
|
||||
}
|
||||
@@ -0,0 +1,602 @@
|
||||
// Owns the one live maths problem and everything derived from it. Shared
|
||||
// state rather than per-request because the whole point of "graph it" and
|
||||
// "explain it" is that they refer to the problem already on the lens; a
|
||||
// caller that re-parsed its own capture each time would make those
|
||||
// follow-ups impossible.
|
||||
//
|
||||
// Deep digit work runs on the phone as an explicit, cancellable long run
|
||||
// the wearer opts into. The
|
||||
// optional AI pass is injected as a hook so this module stays free of any
|
||||
// networking and testable in plain Node.
|
||||
|
||||
import { type MathConstantName, ComputeCancelled, constantDisplayName, constantNamed } from "./constant-digits";
|
||||
import { highlightedMatch } from "./digit-search";
|
||||
import { formatInt } from "./math-number";
|
||||
import {
|
||||
type LongRunOffer,
|
||||
type LongRunProgress,
|
||||
type MathWorkload,
|
||||
compactDuration,
|
||||
longRunOffer as makeLongRunOffer,
|
||||
runAcceptedCount,
|
||||
runAcceptedDigits,
|
||||
runAcceptedSearch,
|
||||
} from "./workload";
|
||||
import { type MathSessionResult, MathSession, parseCommand } from "./session";
|
||||
import { type Graph } from "./plotter";
|
||||
import { type SolutionStep } from "./solver";
|
||||
import { plain } from "./text-renderer";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Branch outcome
|
||||
|
||||
/**
|
||||
* A branch result. The value/failure split matters: a parse error must never
|
||||
* be posted onward as if it were the answer.
|
||||
*/
|
||||
export type MathBranchOutcome =
|
||||
| { kind: "value"; text: string }
|
||||
| { kind: "failure"; reason: string };
|
||||
|
||||
export type MathBranchMode = "solve" | "explain" | "graph" | "derivative" | "digitSearch" | "digitCount";
|
||||
|
||||
/**
|
||||
* The app's uniform gesture contract: forward/back step through the
|
||||
* working, commit
|
||||
* graphs, alternate explains, exit clears.
|
||||
*/
|
||||
export type RingAction = "forward" | "back" | "commit" | "alternate" | "exit";
|
||||
|
||||
/**
|
||||
* Ask the configured assistant to render a spoken problem as an expression
|
||||
* (the prompt text lives in app/prompts.ts with every other prompt).
|
||||
* Injected by the app; null when no provider is configured. Resolves to the
|
||||
* model's raw reply, or null on failure — the coordinator sanitises it.
|
||||
*/
|
||||
export type AICompletion = (spokenText: string) => Promise<string | null>;
|
||||
|
||||
export class MathCoordinator {
|
||||
/** The last thing produced, for the answer view. */
|
||||
lastResult: MathSessionResult | null = null;
|
||||
lastGraph: Graph | null = null;
|
||||
/** Position in the working, for the step indicator. */
|
||||
stepPosition: { index: number; total: number } | null = null;
|
||||
|
||||
/**
|
||||
* A standing offer to grind the full-depth answer out on the phone.
|
||||
* Non-null means every surface should be offering it.
|
||||
*/
|
||||
pendingLongRun: LongRunOffer | null = null;
|
||||
/** Live progress while an accepted run is going. Null when nothing is running. */
|
||||
longRunProgress: LongRunProgress | null = null;
|
||||
/**
|
||||
* The answer a deeper pass produced. One channel, because from the
|
||||
* wearer's side it is one event: the better answer arrived.
|
||||
*/
|
||||
deepAnswer: MathBranchOutcome | null = null;
|
||||
|
||||
/** Repaint hook, set by the owning layer. */
|
||||
onChanged: (() => void) | null = null;
|
||||
|
||||
private readonly session = new MathSession();
|
||||
private completeWithAI: AICompletion | null = null;
|
||||
private longRunCancelled = false;
|
||||
private longRunRunning = false;
|
||||
private longRunStartedAtMs = 0;
|
||||
|
||||
get hasProblem(): boolean {
|
||||
return this.session.hasProblem;
|
||||
}
|
||||
|
||||
get currentSolution() {
|
||||
return this.session.currentSolution;
|
||||
}
|
||||
|
||||
get explanationSteps(): SolutionStep[] {
|
||||
return this.session.currentSolution?.steps ?? [];
|
||||
}
|
||||
|
||||
get isRunningLong(): boolean {
|
||||
return this.longRunRunning;
|
||||
}
|
||||
|
||||
setUsesDegrees(value: boolean): void {
|
||||
this.session.setUsesDegrees(value);
|
||||
}
|
||||
|
||||
setAICompletion(completion: AICompletion | null): void {
|
||||
this.completeWithAI = completion;
|
||||
}
|
||||
|
||||
private changed(): void {
|
||||
this.onChanged?.();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Branch execution
|
||||
|
||||
/**
|
||||
* Run one branch. Returns the glasses text, or a failure string — the
|
||||
* caller distinguishes them.
|
||||
*/
|
||||
run(mode: MathBranchMode, input: string): MathBranchOutcome {
|
||||
const trimmed = input.trim();
|
||||
|
||||
let sessionResult: MathSessionResult;
|
||||
switch (mode) {
|
||||
case "solve":
|
||||
// "Solve it" after Graph/Explain means show the standing answer
|
||||
// again. Requiring fresh input here made the third follow-up mode
|
||||
// uniquely fail.
|
||||
if (!trimmed && this.session.hasProblem) {
|
||||
sessionResult = this.session.execute({ kind: "restate" });
|
||||
} else if (!trimmed) {
|
||||
return { kind: "failure", reason: "Nothing was captured to solve" };
|
||||
} else {
|
||||
sessionResult = this.session.solve(trimmed);
|
||||
}
|
||||
break;
|
||||
case "graph":
|
||||
// A graph branch may fire with a fresh capture ("graph x squared") or
|
||||
// as a follow-up on the standing problem ("graph it"). Both have to
|
||||
// work from the same branch.
|
||||
if (trimmed && (parseCommand(trimmed) === null || this.isProblem(trimmed))) {
|
||||
this.session.solve(trimmed);
|
||||
}
|
||||
sessionResult = this.session.graph();
|
||||
break;
|
||||
case "explain":
|
||||
if (trimmed && this.isProblem(trimmed)) this.session.solve(trimmed);
|
||||
sessionResult = this.session.explain();
|
||||
break;
|
||||
case "derivative":
|
||||
if (trimmed && this.isProblem(trimmed)) this.session.solve(trimmed);
|
||||
sessionResult = this.session.differentiate(null);
|
||||
break;
|
||||
case "digitSearch":
|
||||
case "digitCount": {
|
||||
const digits = MathCoordinator.digitRun(trimmed);
|
||||
if (!digits) return { kind: "failure", reason: "No digits were captured to look for" };
|
||||
// The constant is read from the capture when the wearer named one
|
||||
// ("…in the golden ratio") and is π otherwise.
|
||||
const constant: MathConstantName = constantNamed(trimmed) ?? "pi";
|
||||
sessionResult = this.session.execute({
|
||||
kind: "advanced",
|
||||
topic:
|
||||
mode === "digitCount"
|
||||
? { kind: "digitCount", pattern: digits, constant }
|
||||
: { kind: "digitSearch", pattern: digits, constant, occurrence: 1 },
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return this.publish(sessionResult);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every digit in the capture, in order, with the separators dropped.
|
||||
*
|
||||
* Joined rather than "the first run" because ASR punctuates a spoken date
|
||||
* freely — "07 04 84", "070484", "7/4/84" are all the same six digits —
|
||||
* and taking the first run would search π for "07", which appears within
|
||||
* the first dozen places and looks for all the world like a working
|
||||
* answer.
|
||||
*/
|
||||
static digitRun(text: string): string | null {
|
||||
const joined = text.replace(/\D/g, "");
|
||||
return joined ? joined : null;
|
||||
}
|
||||
|
||||
private isProblem(text: string): boolean {
|
||||
return parseCommand(text)?.kind === "problem";
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Spoken questions
|
||||
|
||||
/**
|
||||
* Answer a question stated in words, whatever shape it arrived in.
|
||||
*
|
||||
* Two passes, in this order and never the other way round:
|
||||
*
|
||||
* 1. The deterministic engine alone. The spoken normaliser already turns
|
||||
* "two x squared plus three x" into `2x²+3x`, and every answer it gives
|
||||
* is exact.
|
||||
* 2. Only if that fails to parse, ask the model to REWRITE the words as an
|
||||
* expression — and then solve that expression here, deterministically.
|
||||
*
|
||||
* The model never computes anything. It is used as a translator from
|
||||
* English into notation, which is the part it is genuinely good at and the
|
||||
* part where a mistake is visible: the rewritten expression is returned
|
||||
* alongside the answer, so a wrong reading shows up as a wrong-looking
|
||||
* equation rather than as a plausible wrong number.
|
||||
*/
|
||||
async answerSpoken(text: string): Promise<MathBranchOutcome> {
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed) return { kind: "failure", reason: "Nothing was said to calculate" };
|
||||
|
||||
const command = parseCommand(trimmed);
|
||||
if (command) {
|
||||
const outcome = this.publish(this.session.execute(command));
|
||||
if (outcome.kind === "value") return outcome;
|
||||
// A FOLLOW-UP that failed keeps its own message. "Graph it" with
|
||||
// nothing on the lens fails because there is nothing to graph, and
|
||||
// handing those two words to a rewriter would replace that with "could
|
||||
// not read that as a calculation" — true of the words, and useless
|
||||
// about the actual problem.
|
||||
if (command.kind !== "problem") return outcome;
|
||||
}
|
||||
|
||||
const rewritten = await this.expressionFromAI(trimmed);
|
||||
if (!rewritten) {
|
||||
return { kind: "failure", reason: "Could not read that as a calculation" };
|
||||
}
|
||||
const outcome = this.publish(this.session.solve(rewritten));
|
||||
if (outcome.kind !== "value") return outcome;
|
||||
// Show the reading, not just the result. A wearer glancing at the lens
|
||||
// has to be able to see that the machine understood the right question
|
||||
// before they repeat the number.
|
||||
return { kind: "value", text: `${rewritten}\n${outcome.text}` };
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask the configured assistant to render a spoken problem as an
|
||||
* expression. Returns null when no provider is configured, when it
|
||||
* declines, or when it answers with anything that is not one.
|
||||
*/
|
||||
private async expressionFromAI(text: string): Promise<string | null> {
|
||||
if (!this.completeWithAI) return null;
|
||||
let raw: string | null;
|
||||
try {
|
||||
raw = await this.completeWithAI(text);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!raw) return null;
|
||||
|
||||
let candidate = raw.trim();
|
||||
// Models fence notation out of habit even when told not to.
|
||||
if (candidate.startsWith("```")) {
|
||||
candidate = candidate
|
||||
.split("\n")
|
||||
.filter((line) => !line.startsWith("```"))
|
||||
.join(" ")
|
||||
.trim();
|
||||
}
|
||||
candidate = candidate.replace(/^[ `.,]+|[ `.,]+$/g, "");
|
||||
|
||||
if (!candidate || candidate.toLowerCase() === "none") return null;
|
||||
// A refusal or an apology is prose, and prose fed to the parser fails in
|
||||
// a way that reads like the maths was wrong rather than the routing.
|
||||
if (candidate.length > 120) return null;
|
||||
if (!/[+\-*/^=\d]/.test(candidate)) return null;
|
||||
return candidate;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Voice follow-ups
|
||||
|
||||
/**
|
||||
* Handle a spoken follow-up. Returns null when the utterance is not a
|
||||
* maths command, so ordinary conversation flows past untouched — this is
|
||||
* called from the transcript stream, which sees everything said in the
|
||||
* room in continuous mode.
|
||||
*/
|
||||
handleUtterance(utterance: string): MathBranchOutcome | null {
|
||||
// A standing offer or a run in flight owns the next yes/no said in the
|
||||
// room. Checked before the maths parser, because "keep going" is not an
|
||||
// equation and would otherwise fall straight through.
|
||||
const longRunAnswer = this.handleLongRunUtterance(utterance);
|
||||
if (longRunAnswer) return longRunAnswer;
|
||||
|
||||
const command = parseCommand(utterance);
|
||||
if (!command) return null;
|
||||
// A bare problem with no standing session is a new problem; a follow-up
|
||||
// with no session is a no-op rather than an error card in mid-air.
|
||||
if (command.kind !== "problem" && command.kind !== "advanced" && !this.session.hasProblem) {
|
||||
return null;
|
||||
}
|
||||
return this.publish(this.session.execute(command));
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept or decline a long run by voice. Only fires while an offer stands
|
||||
* or a run is going, so these phrases stay out of the way of ordinary
|
||||
* conversation the rest of the time.
|
||||
*/
|
||||
handleLongRunUtterance(utterance: string): MathBranchOutcome | null {
|
||||
const text = utterance.toLowerCase();
|
||||
|
||||
if (this.longRunRunning) {
|
||||
if (!STOP_PHRASES.some((phrase) => text.includes(phrase))) return null;
|
||||
this.cancelLongRun();
|
||||
return { kind: "failure", reason: "Stopping" };
|
||||
}
|
||||
|
||||
const offer = this.pendingLongRun;
|
||||
if (!offer) return null;
|
||||
if (ACCEPT_PHRASES.some((phrase) => text.includes(phrase))) {
|
||||
void this.acceptLongRun();
|
||||
return { kind: "value", text: `Working — ${compactDuration(offer.estimatedSeconds)}` };
|
||||
}
|
||||
if (DECLINE_PHRASES.some((phrase) => text.includes(phrase))) {
|
||||
this.declineLongRun();
|
||||
return { kind: "failure", reason: "Left it there" };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
get hasLongRunInteraction(): boolean {
|
||||
return this.pendingLongRun !== null || this.longRunRunning;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Uniform gesture contract
|
||||
|
||||
handleRingAction(action: RingAction): MathBranchOutcome | null {
|
||||
// The offer and the running job both pre-empt the step navigation: while
|
||||
// either is on screen, the input is answering that question and nothing
|
||||
// else. Same gestures, no new vocabulary.
|
||||
if (this.longRunRunning) {
|
||||
if (action !== "exit") return null;
|
||||
this.cancelLongRun();
|
||||
return { kind: "failure", reason: "Stopping" };
|
||||
}
|
||||
const offer = this.pendingLongRun;
|
||||
if (offer) {
|
||||
switch (action) {
|
||||
case "commit":
|
||||
void this.acceptLongRun();
|
||||
return { kind: "value", text: `Working — ${compactDuration(offer.estimatedSeconds)}` };
|
||||
case "exit":
|
||||
this.declineLongRun();
|
||||
return { kind: "failure", reason: "Left it there" };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.session.hasProblem) return null;
|
||||
switch (action) {
|
||||
case "forward":
|
||||
return this.publish(this.session.execute({ kind: "nextStep" }));
|
||||
case "back":
|
||||
return this.publish(this.session.execute({ kind: "previousStep" }));
|
||||
case "commit":
|
||||
return this.publish(this.session.graph());
|
||||
case "alternate":
|
||||
return this.publish(this.session.explain());
|
||||
case "exit":
|
||||
return this.publish(this.session.execute({ kind: "clear" }));
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Long runs
|
||||
|
||||
/** Take the standing offer. Returns false when there was nothing to accept. */
|
||||
acceptLongRun(): boolean {
|
||||
const offer = this.pendingLongRun;
|
||||
if (!offer || this.longRunRunning) return false;
|
||||
this.pendingLongRun = null;
|
||||
this.deepAnswer = null;
|
||||
this.longRunCancelled = false;
|
||||
this.longRunRunning = true;
|
||||
this.longRunStartedAtMs = Date.now();
|
||||
this.longRunProgress = { fraction: 0, stage: "starting", elapsedSeconds: 0 };
|
||||
this.changed();
|
||||
|
||||
const cancellation = () => this.longRunCancelled;
|
||||
const progress = (fraction: number, stage: string) => {
|
||||
this.longRunProgress = {
|
||||
fraction,
|
||||
stage,
|
||||
elapsedSeconds: (Date.now() - this.longRunStartedAtMs) / 1000,
|
||||
};
|
||||
this.changed();
|
||||
};
|
||||
|
||||
void (async () => {
|
||||
let outcome: MathBranchOutcome;
|
||||
try {
|
||||
switch (offer.workload.kind) {
|
||||
case "digitSearch": {
|
||||
const found = await runAcceptedSearch(offer, cancellation, progress);
|
||||
outcome = describeDeepSearch(found, offer.workload.pattern, offer.workload.constant);
|
||||
break;
|
||||
}
|
||||
case "constantDigits": {
|
||||
const digits = await runAcceptedDigits(offer, cancellation, progress);
|
||||
outcome = digits
|
||||
? {
|
||||
kind: "value",
|
||||
text: `${constantDisplayName(offer.workload.constant)}: ${formatInt(digits.length)} digits ready`,
|
||||
}
|
||||
: { kind: "failure", reason: "Could not generate that many digits" };
|
||||
break;
|
||||
}
|
||||
case "digitCount": {
|
||||
const counted = await runAcceptedCount(offer, cancellation, progress);
|
||||
outcome = {
|
||||
kind: "value",
|
||||
text: describeCount(counted.occurrences, counted.searchedDigits, offer.workload.pattern, offer.workload.constant),
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
outcome =
|
||||
error instanceof ComputeCancelled
|
||||
? { kind: "failure", reason: "Stopped" }
|
||||
: { kind: "failure", reason: String((error as Error)?.message ?? error) };
|
||||
}
|
||||
this.longRunRunning = false;
|
||||
this.longRunProgress = null;
|
||||
this.deepAnswer = outcome;
|
||||
this.changed();
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Turn the offer down. The shallow answer already given stands. */
|
||||
declineLongRun(): void {
|
||||
this.pendingLongRun = null;
|
||||
this.changed();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop a run in flight. The digits computed so far are discarded — a
|
||||
* partial expansion cannot answer a position question.
|
||||
*/
|
||||
cancelLongRun(): void {
|
||||
this.longRunCancelled = true;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Publishing
|
||||
|
||||
private publish(sessionResult: MathSessionResult): MathBranchOutcome {
|
||||
this.lastResult = sessionResult;
|
||||
|
||||
// The shallow answer goes out immediately; anything better arrives on
|
||||
// `deepAnswer` if the wearer accepts the standing offer. Never block the
|
||||
// first response on the second — silence is worse than a partial.
|
||||
if (sessionResult.unresolvedWorkload) {
|
||||
this.pendingLongRun = makeLongRunOffer(
|
||||
sessionResult.unresolvedWorkload,
|
||||
"Needs a deeper expansion than the fast pass holds",
|
||||
shallowDescription(sessionResult.unresolvedWorkload, sessionResult),
|
||||
);
|
||||
this.deepAnswer = null;
|
||||
}
|
||||
|
||||
switch (sessionResult.payload.kind) {
|
||||
case "graph":
|
||||
this.lastGraph = sessionResult.payload.graph;
|
||||
this.stepPosition = null;
|
||||
break;
|
||||
case "step":
|
||||
this.lastGraph = null;
|
||||
this.stepPosition = { index: sessionResult.payload.index, total: sessionResult.payload.total };
|
||||
break;
|
||||
case "solution":
|
||||
case "message":
|
||||
case "topic":
|
||||
this.lastGraph = null;
|
||||
// An advanced topic answers in one shot — there is no working to step
|
||||
// through, so the step indicator must clear.
|
||||
this.stepPosition = null;
|
||||
break;
|
||||
case "failure":
|
||||
break;
|
||||
}
|
||||
this.changed();
|
||||
|
||||
if (sessionResult.payload.kind === "failure") {
|
||||
return { kind: "failure", reason: sessionResult.payload.message };
|
||||
}
|
||||
return { kind: "value", text: this.glassesText(sessionResult) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Two or three short rows. The lens has no room for the detail sentence,
|
||||
* which is why `detail` stays in the fuller answer view.
|
||||
*/
|
||||
private glassesText(sessionResult: MathSessionResult): string {
|
||||
switch (sessionResult.payload.kind) {
|
||||
case "step": {
|
||||
const payload = sessionResult.payload;
|
||||
return `${payload.index + 1}/${payload.total} ${payload.step.title}\n${plain(payload.step.expression)}`;
|
||||
}
|
||||
case "graph":
|
||||
// The bitmap carries the picture; this is the text fallback.
|
||||
return sessionResult.headline;
|
||||
case "topic": {
|
||||
// Two field rows at most: the window is short and the headline
|
||||
// already took a line.
|
||||
const payload = sessionResult.payload;
|
||||
return [payload.headline, ...payload.fields.slice(0, 2)].join("\n");
|
||||
}
|
||||
default:
|
||||
return sessionResult.headline;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Long-run phrases
|
||||
|
||||
const ACCEPT_PHRASES = [
|
||||
"keep going",
|
||||
"run it anyway",
|
||||
"run it any way",
|
||||
"take your time",
|
||||
"go deeper",
|
||||
"keep looking",
|
||||
"do it anyway",
|
||||
"yes go on",
|
||||
];
|
||||
|
||||
const DECLINE_PHRASES = [
|
||||
"never mind",
|
||||
"nevermind",
|
||||
"forget it",
|
||||
"leave it",
|
||||
"don't bother",
|
||||
"do not bother",
|
||||
"skip it",
|
||||
];
|
||||
|
||||
const STOP_PHRASES = ["stop", "cancel", "give up", "that's enough", "thats enough"];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Descriptions
|
||||
|
||||
function describeDeepSearch(
|
||||
outcome: Awaited<ReturnType<typeof runAcceptedSearch>>,
|
||||
pattern: string,
|
||||
constant: MathConstantName,
|
||||
): MathBranchOutcome {
|
||||
switch (outcome.kind) {
|
||||
case "found":
|
||||
return {
|
||||
kind: "value",
|
||||
text:
|
||||
`${constantDisplayName(constant)}: places ${outcome.match.start}–${outcome.match.end}\n` +
|
||||
`…${highlightedMatch(outcome.match)}…`,
|
||||
};
|
||||
case "notFound":
|
||||
// Now a much stronger claim than the shallow pass could make, so it is
|
||||
// worth stating the depth that was actually reached.
|
||||
return {
|
||||
kind: "failure",
|
||||
reason:
|
||||
`${pattern} is not in the first ${formatInt(outcome.searchedDigits)} digits ` +
|
||||
`of ${constantDisplayName(constant)}`,
|
||||
};
|
||||
case "invalidPattern":
|
||||
return { kind: "failure", reason: outcome.reason };
|
||||
}
|
||||
}
|
||||
|
||||
function describeCount(
|
||||
occurrences: number,
|
||||
searchedDigits: number,
|
||||
pattern: string,
|
||||
constant: MathConstantName,
|
||||
): string {
|
||||
const times = occurrences === 1 ? "time" : "times";
|
||||
return `${pattern}: ${occurrences} ${times}\nfirst ${formatInt(searchedDigits)} digits of ${constantDisplayName(constant)}`;
|
||||
}
|
||||
|
||||
function shallowDescription(workload: MathWorkload, sessionResult: MathSessionResult): string | null {
|
||||
switch (workload.kind) {
|
||||
case "digitSearch":
|
||||
return sessionResult.headline;
|
||||
case "digitCount":
|
||||
return sessionResult.headline;
|
||||
case "constantDigits":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
// Symbolic differentiation. Every rule is applied structurally and the result
|
||||
// is handed to the simplifier, so `d/dx (x^2)` comes back as `2x` rather than
|
||||
// `2 · x^(2-1) · 1`. That matters because the derivative is user-visible — it
|
||||
// is what "explain it" shows.
|
||||
|
||||
import {
|
||||
type MathExpression,
|
||||
type MathFunction,
|
||||
ONE,
|
||||
ZERO,
|
||||
addExpr,
|
||||
divideExpr,
|
||||
fn,
|
||||
int,
|
||||
multiplyExpr,
|
||||
negate,
|
||||
powerExpr,
|
||||
relation,
|
||||
subtractExpr,
|
||||
variablesOf,
|
||||
} from "./expression";
|
||||
import { simplify } from "./simplifier";
|
||||
import { evaluateValue } from "./evaluator";
|
||||
|
||||
export function differentiate(expression: MathExpression, withRespectTo: string): MathExpression {
|
||||
return simplify(raw(expression, withRespectTo));
|
||||
}
|
||||
|
||||
/** Nth derivative. */
|
||||
export function differentiateOrder(
|
||||
expression: MathExpression,
|
||||
withRespectTo: string,
|
||||
order: number,
|
||||
): MathExpression {
|
||||
let current = expression;
|
||||
for (let step = 0; step < Math.max(0, order); step++) {
|
||||
current = differentiate(current, withRespectTo);
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
function raw(expression: MathExpression, variable: string): MathExpression {
|
||||
switch (expression.type) {
|
||||
case "number":
|
||||
case "constant":
|
||||
return ZERO;
|
||||
|
||||
case "variable":
|
||||
return expression.name === variable ? ONE : ZERO;
|
||||
|
||||
case "negate":
|
||||
return negate(raw(expression.inner, variable));
|
||||
|
||||
case "add":
|
||||
return addExpr(expression.terms.map((term) => raw(term, variable)));
|
||||
|
||||
case "multiply": {
|
||||
// Product rule, generalised: d(abc) = a'bc + ab'c + abc'.
|
||||
const terms: MathExpression[] = [];
|
||||
for (let index = 0; index < expression.factors.length; index++) {
|
||||
const replaced = [...expression.factors];
|
||||
replaced[index] = raw(expression.factors[index]!, variable);
|
||||
terms.push(multiplyExpr(replaced));
|
||||
}
|
||||
return addExpr(terms);
|
||||
}
|
||||
|
||||
case "power":
|
||||
return differentiatePower(expression.base, expression.exponent, variable);
|
||||
|
||||
case "function": {
|
||||
const argument = expression.args[0];
|
||||
if (!argument) return ZERO;
|
||||
const outer = derivativeOfFunction(expression.fn, argument);
|
||||
// Chain rule. Skipping this when the argument is the bare variable
|
||||
// would be a needless special case — the simplifier removes the `· 1`
|
||||
// anyway.
|
||||
return multiplyExpr([outer, raw(argument, variable)]);
|
||||
}
|
||||
|
||||
case "relation":
|
||||
// Differentiating both sides of an equation is implicit
|
||||
// differentiation's first step; useful, and harmless here.
|
||||
return relation(expression.relation, raw(expression.lhs, variable), raw(expression.rhs, variable));
|
||||
}
|
||||
}
|
||||
|
||||
function differentiatePower(
|
||||
base: MathExpression,
|
||||
exponent: MathExpression,
|
||||
variable: string,
|
||||
): MathExpression {
|
||||
const baseHasVariable = variablesOf(base).includes(variable);
|
||||
const exponentHasVariable = variablesOf(exponent).includes(variable);
|
||||
|
||||
if (!baseHasVariable && !exponentHasVariable) return ZERO;
|
||||
|
||||
if (baseHasVariable && !exponentHasVariable) {
|
||||
// Power rule: d(u^n) = n · u^(n-1) · u'
|
||||
const reduced = subtractExpr(exponent, ONE);
|
||||
return multiplyExpr([exponent, powerExpr(base, reduced), raw(base, variable)]);
|
||||
}
|
||||
|
||||
if (!baseHasVariable && exponentHasVariable) {
|
||||
// Exponential rule: d(a^v) = a^v · ln(a) · v'
|
||||
return multiplyExpr([powerExpr(base, exponent), fn("ln", [base]), raw(exponent, variable)]);
|
||||
}
|
||||
|
||||
// General case via logarithmic differentiation:
|
||||
// d(u^v) = u^v · (v' · ln u + v · u'/u)
|
||||
const uv = powerExpr(base, exponent);
|
||||
const firstTerm = multiplyExpr([raw(exponent, variable), fn("ln", [base])]);
|
||||
const secondTerm = multiplyExpr([exponent, divideExpr(raw(base, variable), base)]);
|
||||
return multiplyExpr([uv, addExpr([firstTerm, secondTerm])]);
|
||||
}
|
||||
|
||||
/** The outer derivative only; the caller applies the chain rule. */
|
||||
function derivativeOfFunction(name: MathFunction, argument: MathExpression): MathExpression {
|
||||
switch (name) {
|
||||
case "sin":
|
||||
return fn("cos", [argument]);
|
||||
case "cos":
|
||||
return negate(fn("sin", [argument]));
|
||||
case "tan":
|
||||
// sec² = 1 / cos²
|
||||
return divideExpr(ONE, powerExpr(fn("cos", [argument]), int(2)));
|
||||
case "asin":
|
||||
return divideExpr(ONE, fn("sqrt", [subtractExpr(ONE, powerExpr(argument, int(2)))]));
|
||||
case "acos":
|
||||
return negate(divideExpr(ONE, fn("sqrt", [subtractExpr(ONE, powerExpr(argument, int(2)))])));
|
||||
case "atan":
|
||||
return divideExpr(ONE, addExpr([ONE, powerExpr(argument, int(2))]));
|
||||
case "sinh":
|
||||
return fn("cosh", [argument]);
|
||||
case "cosh":
|
||||
return fn("sinh", [argument]);
|
||||
case "tanh":
|
||||
return divideExpr(ONE, powerExpr(fn("cosh", [argument]), int(2)));
|
||||
case "ln":
|
||||
return divideExpr(ONE, argument);
|
||||
case "log10":
|
||||
return divideExpr(ONE, multiplyExpr([argument, fn("ln", [int(10)])]));
|
||||
case "log2":
|
||||
return divideExpr(ONE, multiplyExpr([argument, fn("ln", [int(2)])]));
|
||||
case "sqrt":
|
||||
return divideExpr(ONE, multiplyExpr([int(2), fn("sqrt", [argument])]));
|
||||
case "cbrt":
|
||||
return divideExpr(ONE, multiplyExpr([int(3), powerExpr(fn("cbrt", [argument]), int(2))]));
|
||||
case "exp":
|
||||
return fn("exp", [argument]);
|
||||
case "abs":
|
||||
// d|u|/du = u/|u| — undefined at zero, which the plotter's
|
||||
// discontinuity handling already copes with.
|
||||
return divideExpr(argument, fn("abs", [argument]));
|
||||
case "floor":
|
||||
case "ceil":
|
||||
case "round":
|
||||
// Zero almost everywhere; the jumps are measure-zero and are not
|
||||
// representable here.
|
||||
return ZERO;
|
||||
case "factorial":
|
||||
// The derivative of the gamma function needs the digamma function,
|
||||
// which this build does not carry. Returning zero would be a lie, so
|
||||
// the caller gets an unevaluated marker instead.
|
||||
return fn("factorial", [argument]);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Numeric integration
|
||||
|
||||
/**
|
||||
* Definite integral by adaptive Simpson's rule.
|
||||
*
|
||||
* Numeric rather than symbolic: symbolic integration needs a Risch-style
|
||||
* algorithm that is far out of proportion to the feature, and a definite
|
||||
* value is what a calculator user actually asks for. (The symbolic table in
|
||||
* symbolic-integral.ts is tried first where it applies.)
|
||||
*/
|
||||
export function integrateNumeric(
|
||||
expression: MathExpression,
|
||||
variable: string,
|
||||
lower: number,
|
||||
upper: number,
|
||||
tolerance = 1e-9,
|
||||
): number | null {
|
||||
if (!Number.isFinite(lower) || !Number.isFinite(upper)) return null;
|
||||
if (lower === upper) return 0;
|
||||
if (lower > upper) {
|
||||
const flipped = integrateNumeric(expression, variable, upper, lower, tolerance);
|
||||
return flipped === null ? null : -flipped;
|
||||
}
|
||||
|
||||
const f = (x: number): number | null => evaluateValue(expression, { [variable]: x });
|
||||
|
||||
const simpson = (a: number, b: number, fa: number, fb: number, fm: number): number =>
|
||||
((b - a) / 6) * (fa + 4 * fm + fb);
|
||||
|
||||
const adaptive = (
|
||||
a: number,
|
||||
b: number,
|
||||
fa: number,
|
||||
fb: number,
|
||||
fm: number,
|
||||
whole: number,
|
||||
depth: number,
|
||||
): number | null => {
|
||||
const m = (a + b) / 2;
|
||||
const leftMid = (a + m) / 2;
|
||||
const rightMid = (m + b) / 2;
|
||||
const flm = f(leftMid);
|
||||
const frm = f(rightMid);
|
||||
if (flm === null || frm === null) return null;
|
||||
const left = simpson(a, m, fa, fm, flm);
|
||||
const right = simpson(m, b, fm, fb, frm);
|
||||
const total = left + right;
|
||||
// Richardson: the Simpson error term is (total - whole) / 15.
|
||||
if (depth <= 0 || Math.abs(total - whole) <= 15 * tolerance) {
|
||||
return total + (total - whole) / 15;
|
||||
}
|
||||
const leftResult = adaptive(a, m, fa, fm, flm, left, depth - 1);
|
||||
if (leftResult === null) return null;
|
||||
const rightResult = adaptive(m, b, fm, fb, frm, right, depth - 1);
|
||||
if (rightResult === null) return null;
|
||||
return leftResult + rightResult;
|
||||
};
|
||||
|
||||
const fa = f(lower);
|
||||
const fb = f(upper);
|
||||
const fm = f((lower + upper) / 2);
|
||||
if (fa === null || fb === null || fm === null) return null;
|
||||
const whole = simpson(lower, upper, fa, fb, fm);
|
||||
return adaptive(lower, upper, fa, fb, fm, whole, 24);
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
// Finds a digit sequence inside the expansion of a constant.
|
||||
//
|
||||
// The position convention is fixed and stated everywhere it is reported:
|
||||
// **decimal places after the point, 1-based**. So the first `11` in π is at
|
||||
// 94–95, because π = 3.(1)4159… and the 94th digit after the point is the
|
||||
// first `1` of that pair. Every off-by-one complaint about this kind of
|
||||
// feature is a convention that was never written down, so it is written down.
|
||||
|
||||
import {
|
||||
type MathConstantName,
|
||||
MAXIMUM_COMPUTED_DIGITS,
|
||||
fractionalDigits,
|
||||
} from "./constant-digits";
|
||||
|
||||
export type DigitCountResult = {
|
||||
occurrences: number;
|
||||
searchedDigits: number;
|
||||
};
|
||||
|
||||
export type DigitMatch = {
|
||||
/** 1-based decimal place of the first digit of the match. */
|
||||
start: number;
|
||||
/** 1-based decimal place of the last digit. */
|
||||
end: number;
|
||||
/** The digits either side, for the reveal. */
|
||||
context: string;
|
||||
/** Where the match sits inside `context`, as an offset. */
|
||||
contextOffset: number;
|
||||
};
|
||||
|
||||
/** `...3421 ·11· 70679...` with the match marked. */
|
||||
export function highlightedMatch(match: DigitMatch, marker = "·"): string {
|
||||
const length = match.end - match.start + 1;
|
||||
if (match.contextOffset < 0 || match.contextOffset + length > match.context.length) {
|
||||
return match.context;
|
||||
}
|
||||
const before = match.context.slice(0, match.contextOffset);
|
||||
const middle = match.context.slice(match.contextOffset, match.contextOffset + length);
|
||||
const after = match.context.slice(match.contextOffset + length);
|
||||
return `${before}${marker}${middle}${marker}${after}`;
|
||||
}
|
||||
|
||||
export type DigitSearchOutcome =
|
||||
| { kind: "found"; match: DigitMatch }
|
||||
/**
|
||||
* Searched the whole available expansion and did not find it. Carries how
|
||||
* far the search actually reached, because "not in π" and "not in the first
|
||||
* 20,000 digits of π" are very different claims and only one of them is
|
||||
* true.
|
||||
*/
|
||||
| { kind: "notFound"; searchedDigits: number }
|
||||
| { kind: "invalidPattern"; reason: string };
|
||||
|
||||
/** How many digits either side of a hit to return. */
|
||||
export const DEFAULT_CONTEXT_RADIUS = 6;
|
||||
|
||||
export type DigitSource = (constant: MathConstantName, count: number) => string | null;
|
||||
|
||||
const DEFAULT_SOURCE: DigitSource = (constant, count) => fractionalDigits(constant, count);
|
||||
|
||||
/** Find the `occurrence`-th appearance of `pattern`. */
|
||||
export function findDigits(
|
||||
pattern: string,
|
||||
constant: MathConstantName,
|
||||
occurrence = 1,
|
||||
requested: number = MAXIMUM_COMPUTED_DIGITS,
|
||||
contextRadius: number = DEFAULT_CONTEXT_RADIUS,
|
||||
digitSource: DigitSource = DEFAULT_SOURCE,
|
||||
): DigitSearchOutcome {
|
||||
const cleaned = pattern.replace(/\D/g, "");
|
||||
if (!cleaned) return { kind: "invalidPattern", reason: "Give a sequence of digits to look for" };
|
||||
if (occurrence < 1) return { kind: "invalidPattern", reason: "Occurrence must be 1 or more" };
|
||||
|
||||
const expansion = digitSource(constant, requested);
|
||||
if (!expansion) return { kind: "notFound", searchedDigits: 0 };
|
||||
|
||||
return locateDigits(cleaned, expansion, occurrence, contextRadius);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search an expansion the caller already has — the path an accepted long run
|
||||
* uses, where the digits come from the deep generator rather than the
|
||||
* shallow cache.
|
||||
*/
|
||||
export function locateDigits(
|
||||
pattern: string,
|
||||
expansion: string,
|
||||
occurrence = 1,
|
||||
contextRadius: number = DEFAULT_CONTEXT_RADIUS,
|
||||
): DigitSearchOutcome {
|
||||
if (pattern.length > expansion.length) {
|
||||
return { kind: "notFound", searchedDigits: expansion.length };
|
||||
}
|
||||
|
||||
let seen = 0;
|
||||
// Plain scan rather than a substring search: overlapping matches count
|
||||
// ("111" contains "11" twice), and indexOf-with-skip would miss the
|
||||
// overlap.
|
||||
for (let index = 0; index <= expansion.length - pattern.length; index++) {
|
||||
let matched = true;
|
||||
for (let offset = 0; offset < pattern.length; offset++) {
|
||||
if (expansion[index + offset] !== pattern[offset]) {
|
||||
matched = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!matched) continue;
|
||||
seen += 1;
|
||||
if (seen !== occurrence) continue;
|
||||
|
||||
const contextStart = Math.max(0, index - contextRadius);
|
||||
const contextEnd = Math.min(expansion.length, index + pattern.length + contextRadius);
|
||||
return {
|
||||
kind: "found",
|
||||
match: {
|
||||
start: index + 1,
|
||||
end: index + pattern.length,
|
||||
context: expansion.slice(contextStart, contextEnd),
|
||||
contextOffset: index - contextStart,
|
||||
},
|
||||
};
|
||||
}
|
||||
return { kind: "notFound", searchedDigits: expansion.length };
|
||||
}
|
||||
|
||||
/** How many times the pattern appears in the available expansion. */
|
||||
export function countDigits(
|
||||
pattern: string,
|
||||
constant: MathConstantName,
|
||||
requested: number = MAXIMUM_COMPUTED_DIGITS,
|
||||
digitSource: DigitSource = DEFAULT_SOURCE,
|
||||
): DigitCountResult {
|
||||
const cleaned = pattern.replace(/\D/g, "");
|
||||
if (!cleaned) return { occurrences: 0, searchedDigits: 0 };
|
||||
const expansion = digitSource(constant, requested);
|
||||
if (!expansion) return { occurrences: 0, searchedDigits: 0 };
|
||||
return countInExpansion(cleaned, expansion);
|
||||
}
|
||||
|
||||
/** Count overlapping occurrences inside an expansion the caller already has. */
|
||||
export function countInExpansion(pattern: string, expansion: string): DigitCountResult {
|
||||
if (pattern.length > expansion.length) {
|
||||
return { occurrences: 0, searchedDigits: expansion.length };
|
||||
}
|
||||
let total = 0;
|
||||
for (let index = 0; index <= expansion.length - pattern.length; index++) {
|
||||
let matched = true;
|
||||
for (let offset = 0; offset < pattern.length; offset++) {
|
||||
if (expansion[index + offset] !== pattern[offset]) {
|
||||
matched = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matched) total += 1;
|
||||
}
|
||||
return { occurrences: total, searchedDigits: expansion.length };
|
||||
}
|
||||
|
||||
/** The digits at a given range of decimal places, 1-based inclusive. */
|
||||
export function digitsAt(
|
||||
constant: MathConstantName,
|
||||
start: number,
|
||||
end: number,
|
||||
digitSource: DigitSource = DEFAULT_SOURCE,
|
||||
): string | null {
|
||||
if (start < 1 || end < start) return null;
|
||||
const expansion = digitSource(constant, end);
|
||||
if (!expansion || expansion.length < end) return null;
|
||||
return expansion.slice(start - 1, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* How deep you would expect to search before a random `length`-digit string
|
||||
* turns up: 10^length places, on average.
|
||||
*
|
||||
* Reported alongside a notFound so the answer is honest about whether the
|
||||
* search was ever likely to succeed — an eight-digit birthday first appears
|
||||
* around the hundred-millionth digit, which no on-device expansion is going
|
||||
* to reach.
|
||||
*/
|
||||
export function expectedFirstPosition(patternLength: number): number | null {
|
||||
if (patternLength <= 0 || patternLength > 18) return null;
|
||||
return Math.pow(10, patternLength);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// Numeric evaluation of an expression tree. Two return paths on purpose:
|
||||
// `evaluateExact` keeps rationals as rationals (so a solution can be shown as
|
||||
// `3/2`), while `evaluateValue` collapses to a plain number for the plotter,
|
||||
// which samples thousands of points and has no use for exactness.
|
||||
|
||||
import {
|
||||
type MathExpression,
|
||||
constantValue,
|
||||
evaluateFunction,
|
||||
functionIsDefined,
|
||||
} from "./expression";
|
||||
import {
|
||||
type MathNumber,
|
||||
add,
|
||||
doubleValue,
|
||||
integer,
|
||||
integerValue,
|
||||
isNegative,
|
||||
isZero,
|
||||
multiply,
|
||||
negated,
|
||||
raisedTo,
|
||||
real,
|
||||
} from "./math-number";
|
||||
|
||||
export type EvaluatorContext = {
|
||||
variables: Record<string, MathNumber>;
|
||||
/**
|
||||
* Radians unless the caller says otherwise. Trig in degrees is a real user
|
||||
* expectation for a calculator, and getting it silently wrong produces
|
||||
* answers that look plausible.
|
||||
*/
|
||||
usesDegrees: boolean;
|
||||
};
|
||||
|
||||
export function radiansContext(): EvaluatorContext {
|
||||
return { variables: {}, usesDegrees: false };
|
||||
}
|
||||
|
||||
export class EvaluationError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "EvaluationError";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate keeping exactness where possible. Throws on a free variable, so
|
||||
* the caller can distinguish "not a number yet" from "evaluates to NaN".
|
||||
*/
|
||||
export function evaluateExact(expression: MathExpression, context: EvaluatorContext = radiansContext()): MathNumber {
|
||||
switch (expression.type) {
|
||||
case "number":
|
||||
return expression.value;
|
||||
|
||||
case "variable": {
|
||||
const value = context.variables[expression.name];
|
||||
if (value === undefined) {
|
||||
throw new EvaluationError(`No value given for ${expression.name}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
case "constant":
|
||||
return real(constantValue(expression.constant));
|
||||
|
||||
case "add":
|
||||
return expression.terms.reduce<MathNumber>(
|
||||
(total, term) => add(total, evaluateExact(term, context)),
|
||||
integer(0),
|
||||
);
|
||||
|
||||
case "multiply":
|
||||
return expression.factors.reduce<MathNumber>(
|
||||
(total, factor) => multiply(total, evaluateExact(factor, context)),
|
||||
integer(1),
|
||||
);
|
||||
|
||||
case "negate":
|
||||
return negated(evaluateExact(expression.inner, context));
|
||||
|
||||
case "power": {
|
||||
const baseValue = evaluateExact(expression.base, context);
|
||||
const exponentValue = evaluateExact(expression.exponent, context);
|
||||
if (isZero(baseValue) && isNegative(exponentValue)) {
|
||||
throw new EvaluationError("Division by zero");
|
||||
}
|
||||
return raisedTo(baseValue, exponentValue);
|
||||
}
|
||||
|
||||
case "function": {
|
||||
const first = expression.args[0];
|
||||
if (!first) throw new EvaluationError(`${expression.fn} needs an argument`);
|
||||
const argument = evaluateExact(first, context);
|
||||
// Integer factorial stays exact; everything else goes through the
|
||||
// floating-point implementation.
|
||||
const argumentInt = integerValue(argument);
|
||||
if (expression.fn === "factorial" && argumentInt !== null && argumentInt >= 0 && argumentInt <= 20) {
|
||||
let total = 1;
|
||||
for (let value = 2; value <= argumentInt; value++) total *= value;
|
||||
return integer(total);
|
||||
}
|
||||
const raw = adjustForDegrees(expression.fn, doubleValue(argument), context);
|
||||
if (!functionIsDefined(expression.fn, raw)) {
|
||||
throw new EvaluationError(`${expression.fn} is undefined there`);
|
||||
}
|
||||
const result = evaluateFunction(expression.fn, raw);
|
||||
if (!Number.isFinite(result)) {
|
||||
throw new EvaluationError(`${expression.fn} is undefined there`);
|
||||
}
|
||||
return adjustResultForDegrees(expression.fn, result, context);
|
||||
}
|
||||
|
||||
case "relation": {
|
||||
const left = doubleValue(evaluateExact(expression.lhs, context));
|
||||
const right = doubleValue(evaluateExact(expression.rhs, context));
|
||||
let holds: boolean;
|
||||
switch (expression.relation) {
|
||||
case "=":
|
||||
holds = left === right;
|
||||
break;
|
||||
case "<":
|
||||
holds = left < right;
|
||||
break;
|
||||
case "<=":
|
||||
holds = left <= right;
|
||||
break;
|
||||
case ">":
|
||||
holds = left > right;
|
||||
break;
|
||||
case ">=":
|
||||
holds = left >= right;
|
||||
break;
|
||||
}
|
||||
return integer(holds ? 1 : 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Plotting path: never throws, returns null where the function is undefined
|
||||
* so the renderer can break the curve instead of drawing a line across the
|
||||
* gap.
|
||||
*/
|
||||
export function evaluateValue(
|
||||
expression: MathExpression,
|
||||
variables: Record<string, number>,
|
||||
usesDegrees = false,
|
||||
): number | null {
|
||||
const context: EvaluatorContext = { variables: {}, usesDegrees };
|
||||
for (const name of Object.keys(variables)) {
|
||||
context.variables[name] = real(variables[name]!);
|
||||
}
|
||||
let result: MathNumber;
|
||||
try {
|
||||
result = evaluateExact(expression, context);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const value = doubleValue(result);
|
||||
return Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Degrees
|
||||
|
||||
function adjustForDegrees(name: string, argument: number, context: EvaluatorContext): number {
|
||||
if (!context.usesDegrees) return argument;
|
||||
switch (name) {
|
||||
case "sin":
|
||||
case "cos":
|
||||
case "tan":
|
||||
return (argument * Math.PI) / 180;
|
||||
default:
|
||||
return argument;
|
||||
}
|
||||
}
|
||||
|
||||
function adjustResultForDegrees(name: string, result: number, context: EvaluatorContext): MathNumber {
|
||||
if (!context.usesDegrees) return real(result);
|
||||
switch (name) {
|
||||
case "asin":
|
||||
case "acos":
|
||||
case "atan":
|
||||
return real((result * 180) / Math.PI);
|
||||
default:
|
||||
return real(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
// The expression tree everything else operates on: evaluation, simplification,
|
||||
// differentiation, solving, rendering, and plotting. A plain discriminated
|
||||
// union so the whole tree is a value — simplification and differentiation can
|
||||
// rebuild subtrees freely, and structural comparison (expressionEquals) gives
|
||||
// the simplifier the like-term matching it leans on heavily.
|
||||
|
||||
import {
|
||||
type MathNumber,
|
||||
integer as makeInteger,
|
||||
fromDecimal,
|
||||
isZero as numberIsZero,
|
||||
isOne as numberIsOne,
|
||||
numberEquals as numbersEqual,
|
||||
} from "./math-number";
|
||||
|
||||
export type MathRelation = "=" | "<" | "<=" | ">" | ">=";
|
||||
|
||||
export type MathConstant = "pi" | "e" | "tau";
|
||||
|
||||
export type MathFunction =
|
||||
| "sin"
|
||||
| "cos"
|
||||
| "tan"
|
||||
| "asin"
|
||||
| "acos"
|
||||
| "atan"
|
||||
| "sinh"
|
||||
| "cosh"
|
||||
| "tanh"
|
||||
| "ln"
|
||||
| "log10"
|
||||
| "log2"
|
||||
| "sqrt"
|
||||
| "cbrt"
|
||||
| "abs"
|
||||
| "exp"
|
||||
| "floor"
|
||||
| "ceil"
|
||||
| "round"
|
||||
| "factorial";
|
||||
|
||||
export const ALL_FUNCTIONS: readonly MathFunction[] = [
|
||||
"sin",
|
||||
"cos",
|
||||
"tan",
|
||||
"asin",
|
||||
"acos",
|
||||
"atan",
|
||||
"sinh",
|
||||
"cosh",
|
||||
"tanh",
|
||||
"ln",
|
||||
"log10",
|
||||
"log2",
|
||||
"sqrt",
|
||||
"cbrt",
|
||||
"abs",
|
||||
"exp",
|
||||
"floor",
|
||||
"ceil",
|
||||
"round",
|
||||
"factorial",
|
||||
];
|
||||
|
||||
export const ALL_CONSTANTS: readonly MathConstant[] = ["pi", "e", "tau"];
|
||||
|
||||
export type MathExpression =
|
||||
| { type: "number"; value: MathNumber }
|
||||
/** A free variable — `x`, `y`, `theta`. */
|
||||
| { type: "variable"; name: string }
|
||||
/**
|
||||
* A named constant with a known value (`pi`, `e`). Kept distinct from
|
||||
* `variable` so "solve for pi" is impossible and `2π` stays exact instead of
|
||||
* becoming 6.283…
|
||||
*/
|
||||
| { type: "constant"; constant: MathConstant }
|
||||
| { type: "add"; terms: MathExpression[] }
|
||||
| { type: "multiply"; factors: MathExpression[] }
|
||||
| { type: "power"; base: MathExpression; exponent: MathExpression }
|
||||
/**
|
||||
* Unary negation. Not folded into `multiply([-1, x])` because the renderers
|
||||
* and the step explanations both want to say "negative x".
|
||||
*/
|
||||
| { type: "negate"; inner: MathExpression }
|
||||
| { type: "function"; fn: MathFunction; args: MathExpression[] }
|
||||
/** An equation or inequality — the root node of anything solvable. */
|
||||
| { type: "relation"; relation: MathRelation; lhs: MathExpression; rhs: MathExpression };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Convenience constructors
|
||||
|
||||
export function num(value: MathNumber): MathExpression {
|
||||
return { type: "number", value };
|
||||
}
|
||||
|
||||
export function int(value: number): MathExpression {
|
||||
return num(makeInteger(value));
|
||||
}
|
||||
|
||||
export function realExpr(value: number): MathExpression {
|
||||
return num(fromDecimal(value));
|
||||
}
|
||||
|
||||
export function variable(name: string): MathExpression {
|
||||
return { type: "variable", name };
|
||||
}
|
||||
|
||||
export function constant(value: MathConstant): MathExpression {
|
||||
return { type: "constant", constant: value };
|
||||
}
|
||||
|
||||
export function addExpr(terms: MathExpression[]): MathExpression {
|
||||
return { type: "add", terms };
|
||||
}
|
||||
|
||||
export function multiplyExpr(factors: MathExpression[]): MathExpression {
|
||||
return { type: "multiply", factors };
|
||||
}
|
||||
|
||||
export function powerExpr(base: MathExpression, exponent: MathExpression): MathExpression {
|
||||
return { type: "power", base, exponent };
|
||||
}
|
||||
|
||||
export function negate(inner: MathExpression): MathExpression {
|
||||
return { type: "negate", inner };
|
||||
}
|
||||
|
||||
export function fn(name: MathFunction, args: MathExpression[]): MathExpression {
|
||||
return { type: "function", fn: name, args };
|
||||
}
|
||||
|
||||
export function relation(rel: MathRelation, lhs: MathExpression, rhs: MathExpression): MathExpression {
|
||||
return { type: "relation", relation: rel, lhs, rhs };
|
||||
}
|
||||
|
||||
export function subtractExpr(lhs: MathExpression, rhs: MathExpression): MathExpression {
|
||||
return addExpr([lhs, negate(rhs)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Division is `a * b^-1` in the tree, which is what makes the simplifier and
|
||||
* the differentiator tractable — the renderers detect the pattern and print a
|
||||
* real fraction, so nothing user-visible degrades.
|
||||
*/
|
||||
export function divideExpr(lhs: MathExpression, rhs: MathExpression): MathExpression {
|
||||
return multiplyExpr([lhs, powerExpr(rhs, int(-1))]);
|
||||
}
|
||||
|
||||
export const ZERO: MathExpression = int(0);
|
||||
export const ONE: MathExpression = int(1);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Introspection
|
||||
|
||||
export function isZeroExpr(expression: MathExpression): boolean {
|
||||
return expression.type === "number" && numberIsZero(expression.value);
|
||||
}
|
||||
|
||||
export function isOneExpr(expression: MathExpression): boolean {
|
||||
return expression.type === "number" && numberIsOne(expression.value);
|
||||
}
|
||||
|
||||
export function numberValue(expression: MathExpression): MathNumber | null {
|
||||
return expression.type === "number" ? expression.value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every free variable in the tree, in first-appearance order. Order matters:
|
||||
* it decides which variable "solve for x" defaults to and which axis a
|
||||
* single-variable graph uses.
|
||||
*/
|
||||
export function variablesOf(expression: MathExpression): string[] {
|
||||
const seen = new Set<string>();
|
||||
const ordered: string[] = [];
|
||||
collectVariables(expression, ordered, seen);
|
||||
return ordered;
|
||||
}
|
||||
|
||||
function collectVariables(expression: MathExpression, ordered: string[], seen: Set<string>): void {
|
||||
switch (expression.type) {
|
||||
case "variable":
|
||||
if (!seen.has(expression.name)) {
|
||||
seen.add(expression.name);
|
||||
ordered.push(expression.name);
|
||||
}
|
||||
break;
|
||||
case "number":
|
||||
case "constant":
|
||||
break;
|
||||
case "add":
|
||||
for (const term of expression.terms) collectVariables(term, ordered, seen);
|
||||
break;
|
||||
case "multiply":
|
||||
for (const factor of expression.factors) collectVariables(factor, ordered, seen);
|
||||
break;
|
||||
case "power":
|
||||
collectVariables(expression.base, ordered, seen);
|
||||
collectVariables(expression.exponent, ordered, seen);
|
||||
break;
|
||||
case "negate":
|
||||
collectVariables(expression.inner, ordered, seen);
|
||||
break;
|
||||
case "function":
|
||||
for (const argument of expression.args) collectVariables(argument, ordered, seen);
|
||||
break;
|
||||
case "relation":
|
||||
collectVariables(expression.lhs, ordered, seen);
|
||||
collectVariables(expression.rhs, ordered, seen);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
export function isRelation(expression: MathExpression): boolean {
|
||||
return expression.type === "relation";
|
||||
}
|
||||
|
||||
/**
|
||||
* Node count — used to pick the simpler of two equivalent forms and to bound
|
||||
* runaway expansion in the simplifier.
|
||||
*/
|
||||
export function complexity(expression: MathExpression): number {
|
||||
switch (expression.type) {
|
||||
case "number":
|
||||
case "variable":
|
||||
case "constant":
|
||||
return 1;
|
||||
case "add":
|
||||
return 1 + expression.terms.reduce((total, term) => total + complexity(term), 0);
|
||||
case "multiply":
|
||||
return 1 + expression.factors.reduce((total, factor) => total + complexity(factor), 0);
|
||||
case "power":
|
||||
return 1 + complexity(expression.base) + complexity(expression.exponent);
|
||||
case "negate":
|
||||
return 1 + complexity(expression.inner);
|
||||
case "function":
|
||||
return 1 + expression.args.reduce((total, argument) => total + complexity(argument), 0);
|
||||
case "relation":
|
||||
return 1 + complexity(expression.lhs) + complexity(expression.rhs);
|
||||
}
|
||||
}
|
||||
|
||||
/** Replace every occurrence of a variable with an expression. */
|
||||
export function substituting(
|
||||
expression: MathExpression,
|
||||
name: string,
|
||||
replacement: MathExpression,
|
||||
): MathExpression {
|
||||
switch (expression.type) {
|
||||
case "variable":
|
||||
return expression.name === name ? replacement : expression;
|
||||
case "number":
|
||||
case "constant":
|
||||
return expression;
|
||||
case "add":
|
||||
return addExpr(expression.terms.map((term) => substituting(term, name, replacement)));
|
||||
case "multiply":
|
||||
return multiplyExpr(expression.factors.map((factor) => substituting(factor, name, replacement)));
|
||||
case "power":
|
||||
return powerExpr(
|
||||
substituting(expression.base, name, replacement),
|
||||
substituting(expression.exponent, name, replacement),
|
||||
);
|
||||
case "negate":
|
||||
return negate(substituting(expression.inner, name, replacement));
|
||||
case "function":
|
||||
return fn(
|
||||
expression.fn,
|
||||
expression.args.map((argument) => substituting(argument, name, replacement)),
|
||||
);
|
||||
case "relation":
|
||||
return relation(
|
||||
expression.relation,
|
||||
substituting(expression.lhs, name, replacement),
|
||||
substituting(expression.rhs, name, replacement),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Structural equality with value-equal numbers (MathNumber compares by
|
||||
* value).
|
||||
*/
|
||||
export function expressionEquals(a: MathExpression, b: MathExpression): boolean {
|
||||
if (a === b) return true;
|
||||
if (a.type !== b.type) return false;
|
||||
switch (a.type) {
|
||||
case "number": {
|
||||
const other = b as Extract<MathExpression, { type: "number" }>;
|
||||
return numbersEqual(a.value, other.value);
|
||||
}
|
||||
case "variable":
|
||||
return a.name === (b as Extract<MathExpression, { type: "variable" }>).name;
|
||||
case "constant":
|
||||
return a.constant === (b as Extract<MathExpression, { type: "constant" }>).constant;
|
||||
case "add": {
|
||||
const other = b as Extract<MathExpression, { type: "add" }>;
|
||||
return listEquals(a.terms, other.terms);
|
||||
}
|
||||
case "multiply": {
|
||||
const other = b as Extract<MathExpression, { type: "multiply" }>;
|
||||
return listEquals(a.factors, other.factors);
|
||||
}
|
||||
case "power": {
|
||||
const other = b as Extract<MathExpression, { type: "power" }>;
|
||||
return expressionEquals(a.base, other.base) && expressionEquals(a.exponent, other.exponent);
|
||||
}
|
||||
case "negate":
|
||||
return expressionEquals(a.inner, (b as Extract<MathExpression, { type: "negate" }>).inner);
|
||||
case "function": {
|
||||
const other = b as Extract<MathExpression, { type: "function" }>;
|
||||
return a.fn === other.fn && listEquals(a.args, other.args);
|
||||
}
|
||||
case "relation": {
|
||||
const other = b as Extract<MathExpression, { type: "relation" }>;
|
||||
return (
|
||||
a.relation === other.relation &&
|
||||
expressionEquals(a.lhs, other.lhs) &&
|
||||
expressionEquals(a.rhs, other.rhs)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function listEquals(a: MathExpression[], b: MathExpression[]): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let index = 0; index < a.length; index++) {
|
||||
if (!expressionEquals(a[index]!, b[index]!)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Relations
|
||||
|
||||
/**
|
||||
* The relation you get by multiplying or dividing both sides by a negative —
|
||||
* the classic inequality mistake, handled explicitly.
|
||||
*/
|
||||
export function flippedRelation(rel: MathRelation): MathRelation {
|
||||
switch (rel) {
|
||||
case "=":
|
||||
return "=";
|
||||
case "<":
|
||||
return ">";
|
||||
case "<=":
|
||||
return ">=";
|
||||
case ">":
|
||||
return "<";
|
||||
case ">=":
|
||||
return "<=";
|
||||
}
|
||||
}
|
||||
|
||||
export function spokenRelation(rel: MathRelation): string {
|
||||
switch (rel) {
|
||||
case "=":
|
||||
return "equals";
|
||||
case "<":
|
||||
return "is less than";
|
||||
case "<=":
|
||||
return "is at most";
|
||||
case ">":
|
||||
return "is greater than";
|
||||
case ">=":
|
||||
return "is at least";
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
|
||||
export function constantValue(value: MathConstant): number {
|
||||
switch (value) {
|
||||
case "pi":
|
||||
return Math.PI;
|
||||
case "e":
|
||||
return Math.E;
|
||||
case "tau":
|
||||
return 2 * Math.PI;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Functions
|
||||
|
||||
export function evaluateFunction(name: MathFunction, argument: number): number {
|
||||
switch (name) {
|
||||
case "sin":
|
||||
return Math.sin(argument);
|
||||
case "cos":
|
||||
return Math.cos(argument);
|
||||
case "tan":
|
||||
return Math.tan(argument);
|
||||
case "asin":
|
||||
return Math.asin(argument);
|
||||
case "acos":
|
||||
return Math.acos(argument);
|
||||
case "atan":
|
||||
return Math.atan(argument);
|
||||
case "sinh":
|
||||
return Math.sinh(argument);
|
||||
case "cosh":
|
||||
return Math.cosh(argument);
|
||||
case "tanh":
|
||||
return Math.tanh(argument);
|
||||
case "ln":
|
||||
return Math.log(argument);
|
||||
case "log10":
|
||||
return Math.log10(argument);
|
||||
case "log2":
|
||||
return Math.log2(argument);
|
||||
case "sqrt":
|
||||
return Math.sqrt(argument);
|
||||
case "cbrt":
|
||||
return Math.cbrt(argument);
|
||||
case "abs":
|
||||
return Math.abs(argument);
|
||||
case "exp":
|
||||
return Math.exp(argument);
|
||||
case "floor":
|
||||
return Math.floor(argument);
|
||||
case "ceil":
|
||||
return Math.ceil(argument);
|
||||
case "round":
|
||||
return Math.round(argument);
|
||||
case "factorial":
|
||||
// Real factorial via the gamma function, so `2.5!` is defined rather
|
||||
// than an error — and so the evaluator has one code path for both.
|
||||
return gamma(argument + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Domain check used by the plotter to break a curve rather than draw a line
|
||||
* through a gap (`ln` left of zero, `tan` at its asymptotes).
|
||||
*/
|
||||
export function functionIsDefined(name: MathFunction, argument: number): boolean {
|
||||
switch (name) {
|
||||
case "ln":
|
||||
case "log10":
|
||||
case "log2":
|
||||
return argument > 0;
|
||||
case "sqrt":
|
||||
return argument >= 0;
|
||||
case "asin":
|
||||
case "acos":
|
||||
return argument >= -1 && argument <= 1;
|
||||
case "factorial":
|
||||
return argument > -1 || Math.round(argument) !== argument;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lanczos approximation of the gamma function (JavaScript has no tgamma).
|
||||
* Accurate to well past the display precision used anywhere in this app.
|
||||
*/
|
||||
export function gamma(x: number): number {
|
||||
if (Number.isNaN(x)) return NaN;
|
||||
if (x === Math.round(x)) {
|
||||
if (x <= 0) return NaN; // poles at non-positive integers
|
||||
if (x <= 171) {
|
||||
let result = 1;
|
||||
for (let k = 2; k < x; k++) result *= k;
|
||||
return result;
|
||||
}
|
||||
return Infinity;
|
||||
}
|
||||
if (x < 0.5) {
|
||||
// Reflection formula.
|
||||
return Math.PI / (Math.sin(Math.PI * x) * gamma(1 - x));
|
||||
}
|
||||
const g = 7;
|
||||
const coefficients = [
|
||||
0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313,
|
||||
-176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6,
|
||||
1.5056327351493116e-7,
|
||||
];
|
||||
const z = x - 1;
|
||||
let sum = coefficients[0]!;
|
||||
for (let index = 1; index < g + 2; index++) {
|
||||
sum += coefficients[index]! / (z + index);
|
||||
}
|
||||
const t = z + g + 0.5;
|
||||
return Math.sqrt(2 * Math.PI) * Math.pow(t, z + 0.5) * Math.exp(-t) * sum;
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
// The parts of geometry the calculator's spoken-question surface reaches:
|
||||
// shapes, triangle-from-sides, and Pythagoras.
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Triangles
|
||||
|
||||
/** A triangle solved from whatever three parts were given. */
|
||||
export type Triangle = {
|
||||
/** Side lengths, opposite the same-named angles. */
|
||||
a: number;
|
||||
b: number;
|
||||
c: number;
|
||||
/** Angles in radians. */
|
||||
angleA: number;
|
||||
angleB: number;
|
||||
angleC: number;
|
||||
};
|
||||
|
||||
export function triangleArea(triangle: Triangle): number {
|
||||
// Heron's formula, in the numerically stable ordering: the naive form
|
||||
// loses most of its precision on a needle-thin triangle.
|
||||
const sides = [triangle.a, triangle.b, triangle.c].sort((p, q) => q - p);
|
||||
const [x, y, z] = [sides[0]!, sides[1]!, sides[2]!];
|
||||
const term = (x + (y + z)) * (z - (x - y)) * (z + (x - y)) * (x + (y - z));
|
||||
return term <= 0 ? 0 : Math.sqrt(term) / 4;
|
||||
}
|
||||
|
||||
export function trianglePerimeter(triangle: Triangle): number {
|
||||
return triangle.a + triangle.b + triangle.c;
|
||||
}
|
||||
|
||||
export function triangleKind(triangle: Triangle): string {
|
||||
const tolerance = 1e-9;
|
||||
const sides = [triangle.a, triangle.b, triangle.c].sort((p, q) => p - q);
|
||||
const descriptors: string[] = [];
|
||||
if (Math.abs(sides[0]! - sides[2]!) < tolerance) {
|
||||
descriptors.push("equilateral");
|
||||
} else if (Math.abs(sides[0]! - sides[1]!) < tolerance || Math.abs(sides[1]! - sides[2]!) < tolerance) {
|
||||
descriptors.push("isosceles");
|
||||
} else {
|
||||
descriptors.push("scalene");
|
||||
}
|
||||
const largest = Math.max(triangle.angleA, triangle.angleB, triangle.angleC);
|
||||
if (Math.abs(largest - Math.PI / 2) < 1e-6) {
|
||||
descriptors.push("right");
|
||||
} else if (largest > Math.PI / 2) {
|
||||
descriptors.push("obtuse");
|
||||
} else {
|
||||
descriptors.push("acute");
|
||||
}
|
||||
return descriptors.join(", ");
|
||||
}
|
||||
|
||||
export function triangleAnglesInDegrees(triangle: Triangle): [number, number, number] {
|
||||
return [
|
||||
(triangle.angleA * 180) / Math.PI,
|
||||
(triangle.angleB * 180) / Math.PI,
|
||||
(triangle.angleC * 180) / Math.PI,
|
||||
];
|
||||
}
|
||||
|
||||
export type TriangleResult =
|
||||
| { kind: "one"; triangle: Triangle }
|
||||
/**
|
||||
* SSA can genuinely produce two valid triangles. Returning one and calling
|
||||
* it solved is the classic wrong answer in this topic.
|
||||
*/
|
||||
| { kind: "two"; first: Triangle; second: Triangle }
|
||||
| { kind: "impossible"; reason: string };
|
||||
|
||||
/**
|
||||
* Guards acos/asin against a value a hair outside [-1, 1] from rounding,
|
||||
* which returns NaN and poisons everything downstream.
|
||||
*/
|
||||
function clampedToUnit(value: number): number {
|
||||
return Math.min(1, Math.max(-1, value));
|
||||
}
|
||||
|
||||
/** Three sides. */
|
||||
export function triangleFromSides(a: number, b: number, c: number): TriangleResult {
|
||||
if (a <= 0 || b <= 0 || c <= 0) return { kind: "impossible", reason: "Sides must be positive" };
|
||||
if (a + b <= c || b + c <= a || a + c <= b) {
|
||||
return { kind: "impossible", reason: "Those sides cannot close a triangle" };
|
||||
}
|
||||
const angleA = Math.acos(clampedToUnit((b * b + c * c - a * a) / (2 * b * c)));
|
||||
const angleB = Math.acos(clampedToUnit((a * a + c * c - b * b) / (2 * a * c)));
|
||||
return {
|
||||
kind: "one",
|
||||
triangle: { a, b, c, angleA, angleB, angleC: Math.PI - angleA - angleB },
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shapes
|
||||
|
||||
export type Shape =
|
||||
| { kind: "circle"; radius: number }
|
||||
| { kind: "rectangle"; width: number; height: number }
|
||||
| { kind: "square"; side: number }
|
||||
| { kind: "triangleBaseHeight"; base: number; height: number }
|
||||
| { kind: "trapezoid"; a: number; b: number; height: number }
|
||||
| { kind: "parallelogram"; base: number; height: number }
|
||||
| { kind: "regularPolygon"; sides: number; sideLength: number }
|
||||
| { kind: "ellipse"; a: number; b: number }
|
||||
// Solids
|
||||
| { kind: "sphere"; radius: number }
|
||||
| { kind: "cylinder"; radius: number; height: number }
|
||||
| { kind: "cone"; radius: number; height: number }
|
||||
| { kind: "cube"; side: number }
|
||||
| { kind: "rectangularPrism"; length: number; width: number; height: number }
|
||||
| { kind: "pyramid"; baseArea: number; height: number };
|
||||
|
||||
export function shapeName(shape: Shape): string {
|
||||
switch (shape.kind) {
|
||||
case "circle":
|
||||
return "circle";
|
||||
case "rectangle":
|
||||
return "rectangle";
|
||||
case "square":
|
||||
return "square";
|
||||
case "triangleBaseHeight":
|
||||
return "triangle";
|
||||
case "trapezoid":
|
||||
return "trapezoid";
|
||||
case "parallelogram":
|
||||
return "parallelogram";
|
||||
case "regularPolygon":
|
||||
return `regular ${shape.sides}-gon`;
|
||||
case "ellipse":
|
||||
return "ellipse";
|
||||
case "sphere":
|
||||
return "sphere";
|
||||
case "cylinder":
|
||||
return "cylinder";
|
||||
case "cone":
|
||||
return "cone";
|
||||
case "cube":
|
||||
return "cube";
|
||||
case "rectangularPrism":
|
||||
return "rectangular prism";
|
||||
case "pyramid":
|
||||
return "pyramid";
|
||||
}
|
||||
}
|
||||
|
||||
export function shapeIsSolid(shape: Shape): boolean {
|
||||
switch (shape.kind) {
|
||||
case "sphere":
|
||||
case "cylinder":
|
||||
case "cone":
|
||||
case "cube":
|
||||
case "rectangularPrism":
|
||||
case "pyramid":
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Area for a plane figure; surface area for a solid. */
|
||||
export function shapeArea(shape: Shape): number | null {
|
||||
switch (shape.kind) {
|
||||
case "circle":
|
||||
return Math.PI * shape.radius * shape.radius;
|
||||
case "rectangle":
|
||||
return shape.width * shape.height;
|
||||
case "square":
|
||||
return shape.side * shape.side;
|
||||
case "triangleBaseHeight":
|
||||
return (shape.base * shape.height) / 2;
|
||||
case "trapezoid":
|
||||
return ((shape.a + shape.b) * shape.height) / 2;
|
||||
case "parallelogram":
|
||||
return shape.base * shape.height;
|
||||
case "regularPolygon":
|
||||
return shape.sides >= 3
|
||||
? (shape.sides * shape.sideLength * shape.sideLength) / (4 * Math.tan(Math.PI / shape.sides))
|
||||
: null;
|
||||
case "ellipse":
|
||||
return Math.PI * shape.a * shape.b;
|
||||
case "sphere":
|
||||
return 4 * Math.PI * shape.radius * shape.radius;
|
||||
case "cylinder":
|
||||
return 2 * Math.PI * shape.radius * (shape.radius + shape.height);
|
||||
case "cone":
|
||||
return (
|
||||
Math.PI *
|
||||
shape.radius *
|
||||
(shape.radius + Math.sqrt(shape.radius * shape.radius + shape.height * shape.height))
|
||||
);
|
||||
case "cube":
|
||||
return 6 * shape.side * shape.side;
|
||||
case "rectangularPrism":
|
||||
return (
|
||||
2 *
|
||||
(shape.length * shape.width + shape.length * shape.height + shape.width * shape.height)
|
||||
);
|
||||
case "pyramid":
|
||||
return null; // needs the base shape, not just its area
|
||||
}
|
||||
}
|
||||
|
||||
export function shapePerimeter(shape: Shape): number | null {
|
||||
switch (shape.kind) {
|
||||
case "circle":
|
||||
return 2 * Math.PI * shape.radius;
|
||||
case "rectangle":
|
||||
return 2 * (shape.width + shape.height);
|
||||
case "square":
|
||||
return 4 * shape.side;
|
||||
case "regularPolygon":
|
||||
return shape.sides >= 3 ? shape.sides * shape.sideLength : null;
|
||||
case "ellipse": {
|
||||
// Ramanujan's second approximation — accurate to ~1e-9 for any
|
||||
// realistic eccentricity, where the naive π(a+b) is not close.
|
||||
const h = ((shape.a - shape.b) * (shape.a - shape.b)) / ((shape.a + shape.b) * (shape.a + shape.b));
|
||||
return Math.PI * (shape.a + shape.b) * (1 + (3 * h) / (10 + Math.sqrt(4 - 3 * h)));
|
||||
}
|
||||
default:
|
||||
// Trapezoid/triangle/parallelogram need every side, and the constructor
|
||||
// only took the measurements the area formula uses. Solids have none.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function shapeVolume(shape: Shape): number | null {
|
||||
switch (shape.kind) {
|
||||
case "sphere":
|
||||
return (4 / 3) * Math.PI * shape.radius * shape.radius * shape.radius;
|
||||
case "cylinder":
|
||||
return Math.PI * shape.radius * shape.radius * shape.height;
|
||||
case "cone":
|
||||
return (Math.PI * shape.radius * shape.radius * shape.height) / 3;
|
||||
case "cube":
|
||||
return shape.side * shape.side * shape.side;
|
||||
case "rectangularPrism":
|
||||
return shape.length * shape.width * shape.height;
|
||||
case "pyramid":
|
||||
return (shape.baseArea * shape.height) / 3;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Everything known, for the readback. */
|
||||
export function shapeSummary(shape: Shape): [string, number][] {
|
||||
const parts: [string, number][] = [];
|
||||
const area = shapeArea(shape);
|
||||
if (area !== null) parts.push([shapeIsSolid(shape) ? "Surface area" : "Area", area]);
|
||||
const perimeter = shapePerimeter(shape);
|
||||
if (perimeter !== null) parts.push(["Perimeter", perimeter]);
|
||||
const volume = shapeVolume(shape);
|
||||
if (volume !== null) parts.push(["Volume", volume]);
|
||||
return parts;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Coordinate geometry
|
||||
|
||||
/** Pythagoras, either direction: give any two, get the third. */
|
||||
export function pythagoras(
|
||||
a: number | null,
|
||||
b: number | null,
|
||||
hypotenuse: number | null,
|
||||
): number | null {
|
||||
if (a !== null && b !== null && hypotenuse === null) return Math.sqrt(a * a + b * b);
|
||||
if (a !== null && b === null && hypotenuse !== null) {
|
||||
return hypotenuse > a ? Math.sqrt(hypotenuse * hypotenuse - a * a) : null;
|
||||
}
|
||||
if (a === null && b !== null && hypotenuse !== null) {
|
||||
return hypotenuse > b ? Math.sqrt(hypotenuse * hypotenuse - b * b) : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
// Tokeniser for typed and normalised spoken maths expressions.
|
||||
|
||||
import { type MathNumber, fromDecimal, integer, real } from "./math-number";
|
||||
import { type MathRelation } from "./expression";
|
||||
|
||||
export type MathToken =
|
||||
| { type: "number"; value: MathNumber }
|
||||
| { type: "identifier"; name: string }
|
||||
| { type: "plus" }
|
||||
| { type: "minus" }
|
||||
| { type: "star" }
|
||||
| { type: "slash" }
|
||||
| { type: "percent" }
|
||||
| { type: "caret" }
|
||||
| { type: "bang" }
|
||||
| { type: "leftParen" }
|
||||
| { type: "rightParen" }
|
||||
| { type: "pipe" }
|
||||
| { type: "comma" }
|
||||
| { type: "relation"; relation: MathRelation };
|
||||
|
||||
export type MathParseErrorKind =
|
||||
| { kind: "unexpectedCharacter"; character: string }
|
||||
| { kind: "unexpectedToken"; token: string }
|
||||
| { kind: "unexpectedEnd" }
|
||||
| { kind: "unbalancedParenthesis" }
|
||||
| { kind: "unknownFunction"; name: string }
|
||||
| { kind: "emptyInput" }
|
||||
| { kind: "tooComplex" };
|
||||
|
||||
/**
|
||||
* A parse failure with the user's own words attached, so an error can quote
|
||||
* back what was actually said rather than leaving the wearer guessing which
|
||||
* word broke.
|
||||
*/
|
||||
export class MathParseError extends Error {
|
||||
readonly errorKind: MathParseErrorKind;
|
||||
/** What the user actually said. */
|
||||
readonly context: string;
|
||||
|
||||
constructor(errorKind: MathParseErrorKind, context = "") {
|
||||
super(describeParseError(errorKind, context));
|
||||
this.name = "MathParseError";
|
||||
this.errorKind = errorKind;
|
||||
this.context = context;
|
||||
}
|
||||
}
|
||||
|
||||
/** Written for someone reading a lens mid-task, not for a log. */
|
||||
export function describeParseError(kind: MathParseErrorKind, context: string): string {
|
||||
const quoted = context ? `“${context}”` : "that expression";
|
||||
switch (kind.kind) {
|
||||
case "unexpectedCharacter":
|
||||
return `Could not read "${kind.character}" in ${quoted}`;
|
||||
case "unexpectedToken":
|
||||
return `Did not expect "${kind.token}" in ${quoted}`;
|
||||
case "unexpectedEnd":
|
||||
return `${quoted} is incomplete`;
|
||||
case "unbalancedParenthesis":
|
||||
return `Brackets do not balance in ${quoted}`;
|
||||
case "unknownFunction":
|
||||
return `"${kind.name}" is not a function this build knows`;
|
||||
case "emptyInput":
|
||||
return "Nothing to solve";
|
||||
case "tooComplex":
|
||||
return "That expression is too deeply nested";
|
||||
}
|
||||
}
|
||||
|
||||
function isDigit(character: string): boolean {
|
||||
return character >= "0" && character <= "9";
|
||||
}
|
||||
|
||||
function isLetter(character: string): boolean {
|
||||
return /\p{L}/u.test(character);
|
||||
}
|
||||
|
||||
export function tokenize(input: string): MathToken[] {
|
||||
const tokens: MathToken[] = [];
|
||||
const characters = Array.from(input);
|
||||
let index = 0;
|
||||
|
||||
while (index < characters.length) {
|
||||
const character = characters[index]!;
|
||||
|
||||
if (/\s/.test(character)) {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isDigit(character) || (character === "." && index + 1 < characters.length && isDigit(characters[index + 1]!))) {
|
||||
let literal = "";
|
||||
let sawDot = false;
|
||||
while (index < characters.length) {
|
||||
const next = characters[index]!;
|
||||
if (isDigit(next)) {
|
||||
literal += next;
|
||||
} else if (next === "." && !sawDot) {
|
||||
sawDot = true;
|
||||
literal += next;
|
||||
} else if (next === "," && index + 1 < characters.length && isDigit(characters[index + 1]!)) {
|
||||
// Thousands separator inside a literal: 1,000
|
||||
index += 1;
|
||||
continue;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
// Decimals become exact rationals so later arithmetic stays exact:
|
||||
// 0.25 behaves as 1/4, not as a float.
|
||||
if (sawDot) {
|
||||
tokens.push({ type: "number", value: fromDecimal(Number(literal) || 0) });
|
||||
} else {
|
||||
const parsed = Number(literal);
|
||||
// Exact for every safe literal; anything larger degrades to a real
|
||||
// instead of losing digits silently.
|
||||
tokens.push({
|
||||
type: "number",
|
||||
value: Number.isSafeInteger(parsed) ? integer(parsed) : real(parsed),
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isLetter(character) || character === "_") {
|
||||
let name = "";
|
||||
while (
|
||||
index < characters.length &&
|
||||
(isLetter(characters[index]!) || isDigit(characters[index]!) || characters[index] === "_")
|
||||
) {
|
||||
name += characters[index];
|
||||
index += 1;
|
||||
}
|
||||
tokens.push({ type: "identifier", name });
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (character) {
|
||||
case "+":
|
||||
tokens.push({ type: "plus" });
|
||||
break;
|
||||
case "-":
|
||||
case "−": // ASCII and Unicode minus
|
||||
tokens.push({ type: "minus" });
|
||||
break;
|
||||
case "*":
|
||||
case "×":
|
||||
case "⋅":
|
||||
tokens.push({ type: "star" });
|
||||
break;
|
||||
case "/":
|
||||
case "÷":
|
||||
tokens.push({ type: "slash" });
|
||||
break;
|
||||
case "%":
|
||||
tokens.push({ type: "percent" });
|
||||
break;
|
||||
case "^":
|
||||
tokens.push({ type: "caret" });
|
||||
break;
|
||||
case "!":
|
||||
tokens.push({ type: "bang" });
|
||||
break;
|
||||
case "(":
|
||||
case "[":
|
||||
case "{":
|
||||
tokens.push({ type: "leftParen" });
|
||||
break;
|
||||
case ")":
|
||||
case "]":
|
||||
case "}":
|
||||
tokens.push({ type: "rightParen" });
|
||||
break;
|
||||
case "|":
|
||||
tokens.push({ type: "pipe" });
|
||||
break;
|
||||
case ",":
|
||||
tokens.push({ type: "comma" });
|
||||
break;
|
||||
case "=":
|
||||
// "==" from a typed source is still equality.
|
||||
if (index + 1 < characters.length && characters[index + 1] === "=") index += 1;
|
||||
tokens.push({ type: "relation", relation: "=" });
|
||||
break;
|
||||
case "<":
|
||||
if (index + 1 < characters.length && characters[index + 1] === "=") {
|
||||
tokens.push({ type: "relation", relation: "<=" });
|
||||
index += 1;
|
||||
} else {
|
||||
tokens.push({ type: "relation", relation: "<" });
|
||||
}
|
||||
break;
|
||||
case ">":
|
||||
if (index + 1 < characters.length && characters[index + 1] === "=") {
|
||||
tokens.push({ type: "relation", relation: ">=" });
|
||||
index += 1;
|
||||
} else {
|
||||
tokens.push({ type: "relation", relation: ">" });
|
||||
}
|
||||
break;
|
||||
case "≤":
|
||||
tokens.push({ type: "relation", relation: "<=" });
|
||||
break;
|
||||
case "≥":
|
||||
tokens.push({ type: "relation", relation: ">=" });
|
||||
break;
|
||||
case "√":
|
||||
tokens.push({ type: "identifier", name: "sqrt" });
|
||||
break;
|
||||
case "π":
|
||||
tokens.push({ type: "identifier", name: "pi" });
|
||||
break;
|
||||
default:
|
||||
throw new MathParseError({ kind: "unexpectedCharacter", character }, input);
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
|
||||
if (tokens.length === 0) throw new MathParseError({ kind: "emptyInput" }, input);
|
||||
return tokens;
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
// A numeric literal that stays exact for as long as it can. Rationals rather
|
||||
// than floats everywhere is the difference between a step-by-step solution
|
||||
// that reads `x = 3/2` and one that reads `x = 1.5`, and between
|
||||
// `1/3 + 1/3 + 1/3 = 1` and `0.9999999999999999`. Anything genuinely
|
||||
// irrational (a square root, a sine) degrades to `real` and stays there.
|
||||
//
|
||||
// Number.isSafeInteger is the overflow guard: an operation whose exact
|
||||
// result leaves the safe-integer range falls back to a `real` value rather
|
||||
// than silently losing precision.
|
||||
|
||||
export type MathNumber =
|
||||
| { kind: "integer"; value: number }
|
||||
| { kind: "rational"; n: number; d: number }
|
||||
| { kind: "real"; value: number };
|
||||
|
||||
export function integer(value: number): MathNumber {
|
||||
return { kind: "integer", value };
|
||||
}
|
||||
|
||||
export function real(value: number): MathNumber {
|
||||
return { kind: "real", value };
|
||||
}
|
||||
|
||||
/**
|
||||
* Always stored normalised: `d > 1`, sign on the numerator, gcd(n, d) === 1.
|
||||
* Construct rationals only through here.
|
||||
*/
|
||||
export function rational(numerator: number, denominator: number): MathNumber {
|
||||
if (denominator === 0) return real(NaN);
|
||||
if (!Number.isSafeInteger(numerator) || !Number.isSafeInteger(denominator)) {
|
||||
return real(numerator / denominator);
|
||||
}
|
||||
let n = numerator;
|
||||
let d = denominator;
|
||||
if (d < 0) {
|
||||
n = -n;
|
||||
d = -d;
|
||||
}
|
||||
const divisor = greatestCommonDivisor(Math.abs(n), d);
|
||||
if (divisor > 1) {
|
||||
n /= divisor;
|
||||
d /= divisor;
|
||||
}
|
||||
return d === 1 ? integer(n) : { kind: "rational", n, d };
|
||||
}
|
||||
|
||||
/**
|
||||
* Recover an exact rational from a decimal literal so `0.25` behaves like
|
||||
* `1/4` in later arithmetic. Bounded denominator: beyond that the value is
|
||||
* almost certainly a measurement rather than a fraction, and pretending
|
||||
* otherwise produces absurd numerators. (Stern-Brocot search.)
|
||||
*/
|
||||
export function fromDecimal(value: number, maximumDenominator = 1_000_000): MathNumber {
|
||||
if (!Number.isFinite(value)) return real(value);
|
||||
if (value === Math.round(value) && Number.isSafeInteger(value)) {
|
||||
return integer(value);
|
||||
}
|
||||
let lowerN = 0;
|
||||
let lowerD = 1;
|
||||
let upperN = 1;
|
||||
let upperD = 0;
|
||||
const negative = value < 0;
|
||||
const target = Math.abs(value);
|
||||
for (let iterations = 0; iterations < 64; iterations++) {
|
||||
const mediantN = lowerN + upperN;
|
||||
const mediantD = lowerD + upperD;
|
||||
if (mediantD > maximumDenominator) break;
|
||||
const mediant = mediantN / mediantD;
|
||||
if (Math.abs(mediant - target) < 1e-12) {
|
||||
return rational(negative ? -mediantN : mediantN, mediantD);
|
||||
}
|
||||
if (mediant < target) {
|
||||
lowerN = mediantN;
|
||||
lowerD = mediantD;
|
||||
} else {
|
||||
upperN = mediantN;
|
||||
upperD = mediantD;
|
||||
}
|
||||
}
|
||||
return real(value);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Inspection
|
||||
|
||||
export function doubleValue(value: MathNumber): number {
|
||||
switch (value.kind) {
|
||||
case "integer":
|
||||
return value.value;
|
||||
case "rational":
|
||||
return value.n / value.d;
|
||||
case "real":
|
||||
return value.value;
|
||||
}
|
||||
}
|
||||
|
||||
export function isZero(value: MathNumber): boolean {
|
||||
switch (value.kind) {
|
||||
case "integer":
|
||||
return value.value === 0;
|
||||
case "rational":
|
||||
return value.n === 0;
|
||||
case "real":
|
||||
return value.value === 0;
|
||||
}
|
||||
}
|
||||
|
||||
export function isOne(value: MathNumber): boolean {
|
||||
switch (value.kind) {
|
||||
case "integer":
|
||||
return value.value === 1;
|
||||
case "rational":
|
||||
return false; // normalised, so never 1
|
||||
case "real":
|
||||
return value.value === 1;
|
||||
}
|
||||
}
|
||||
|
||||
export function isNegative(value: MathNumber): boolean {
|
||||
switch (value.kind) {
|
||||
case "integer":
|
||||
return value.value < 0;
|
||||
case "rational":
|
||||
return value.n < 0;
|
||||
case "real":
|
||||
return value.value < 0;
|
||||
}
|
||||
}
|
||||
|
||||
export function isExact(value: MathNumber): boolean {
|
||||
return value.kind !== "real";
|
||||
}
|
||||
|
||||
export function isInteger(value: MathNumber): boolean {
|
||||
return value.kind === "integer";
|
||||
}
|
||||
|
||||
export function integerValue(value: MathNumber): number | null {
|
||||
return value.kind === "integer" ? value.value : null;
|
||||
}
|
||||
|
||||
function asFraction(value: MathNumber): [number, number] | null {
|
||||
switch (value.kind) {
|
||||
case "integer":
|
||||
return [value.value, 1];
|
||||
case "rational":
|
||||
return [value.n, value.d];
|
||||
case "real":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Arithmetic
|
||||
//
|
||||
// Exactness is preserved whenever both operands are exact; a single `real`
|
||||
// anywhere makes the whole result `real`. Overflow falls back to `real`
|
||||
// rather than trapping — a solver exploring a bad branch must not crash the
|
||||
// app on the wearer's face.
|
||||
|
||||
function safeProducts(...values: number[]): boolean {
|
||||
return values.every((value) => Number.isSafeInteger(value));
|
||||
}
|
||||
|
||||
export function add(lhs: MathNumber, rhs: MathNumber): MathNumber {
|
||||
const left = asFraction(lhs);
|
||||
const right = asFraction(rhs);
|
||||
if (!left || !right) return real(doubleValue(lhs) + doubleValue(rhs));
|
||||
const [ln, ld] = left;
|
||||
const [rn, rd] = right;
|
||||
const crossLeft = ln * rd;
|
||||
const crossRight = rn * ld;
|
||||
const numerator = crossLeft + crossRight;
|
||||
const denominator = ld * rd;
|
||||
if (!safeProducts(crossLeft, crossRight, numerator, denominator)) {
|
||||
return real(doubleValue(lhs) + doubleValue(rhs));
|
||||
}
|
||||
return rational(numerator, denominator);
|
||||
}
|
||||
|
||||
export function subtract(lhs: MathNumber, rhs: MathNumber): MathNumber {
|
||||
return add(lhs, negated(rhs));
|
||||
}
|
||||
|
||||
export function multiply(lhs: MathNumber, rhs: MathNumber): MathNumber {
|
||||
const left = asFraction(lhs);
|
||||
const right = asFraction(rhs);
|
||||
if (!left || !right) return real(doubleValue(lhs) * doubleValue(rhs));
|
||||
const [ln, ld] = left;
|
||||
const [rn, rd] = right;
|
||||
const numerator = ln * rn;
|
||||
const denominator = ld * rd;
|
||||
if (!safeProducts(numerator, denominator)) {
|
||||
return real(doubleValue(lhs) * doubleValue(rhs));
|
||||
}
|
||||
return rational(numerator, denominator);
|
||||
}
|
||||
|
||||
export function divide(lhs: MathNumber, rhs: MathNumber): MathNumber {
|
||||
if (isZero(rhs)) return real(doubleValue(lhs) / doubleValue(rhs));
|
||||
const left = asFraction(lhs);
|
||||
const right = asFraction(rhs);
|
||||
if (!left || !right) return real(doubleValue(lhs) / doubleValue(rhs));
|
||||
const [ln, ld] = left;
|
||||
const [rn, rd] = right;
|
||||
const numerator = ln * rd;
|
||||
const denominator = ld * rn;
|
||||
if (!safeProducts(numerator, denominator)) {
|
||||
return real(doubleValue(lhs) / doubleValue(rhs));
|
||||
}
|
||||
return rational(numerator, denominator);
|
||||
}
|
||||
|
||||
export function negated(value: MathNumber): MathNumber {
|
||||
switch (value.kind) {
|
||||
case "integer":
|
||||
return integer(-value.value);
|
||||
case "rational":
|
||||
return { kind: "rational", n: -value.n, d: value.d };
|
||||
case "real":
|
||||
return real(-value.value);
|
||||
}
|
||||
}
|
||||
|
||||
export function reciprocal(value: MathNumber): MathNumber {
|
||||
switch (value.kind) {
|
||||
case "integer":
|
||||
return rational(1, value.value);
|
||||
case "rational":
|
||||
return rational(value.d, value.n);
|
||||
case "real":
|
||||
return real(1 / value.value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact only when the result stays rational — an integer exponent, or a
|
||||
* perfect root. `2^0.5` is irrational, so it becomes `real`.
|
||||
*/
|
||||
export function raisedTo(base: MathNumber, exponent: MathNumber): MathNumber {
|
||||
const fraction = asFraction(base);
|
||||
const power = integerValue(exponent);
|
||||
if (power !== null && fraction) {
|
||||
const [n, d] = fraction;
|
||||
if (power >= 0 && power < 64) {
|
||||
let numerator = 1;
|
||||
let denominator = 1;
|
||||
let overflow = false;
|
||||
for (let step = 0; step < power; step++) {
|
||||
numerator *= n;
|
||||
denominator *= d;
|
||||
if (!safeProducts(numerator, denominator)) {
|
||||
overflow = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!overflow) return rational(numerator, denominator);
|
||||
} else if (power < 0 && power > -64 && !isZero(base)) {
|
||||
return raisedTo(reciprocal(base), integer(-power));
|
||||
}
|
||||
}
|
||||
// An exact root of a perfect power stays exact: sqrt(9/4) = 3/2.
|
||||
if (exponent.kind === "rational" && exponent.d === 2 && exponent.n === 1 && fraction) {
|
||||
const [n, d] = fraction;
|
||||
if (n >= 0) {
|
||||
const rootN = Math.round(Math.sqrt(n));
|
||||
const rootD = Math.round(Math.sqrt(d));
|
||||
if (rootN * rootN === n && rootD * rootD === d) return rational(rootN, rootD);
|
||||
}
|
||||
}
|
||||
return real(Math.pow(doubleValue(base), doubleValue(exponent)));
|
||||
}
|
||||
|
||||
export function greatestCommonDivisor(a: number, b: number): number {
|
||||
let x = Math.abs(a);
|
||||
let y = Math.abs(b);
|
||||
while (y !== 0) {
|
||||
const next = x % y;
|
||||
x = y;
|
||||
y = next;
|
||||
}
|
||||
return x === 0 ? 1 : x;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Comparison
|
||||
|
||||
export function lessThan(lhs: MathNumber, rhs: MathNumber): boolean {
|
||||
return doubleValue(lhs) < doubleValue(rhs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Structural equality would make `integer(1)` differ from `real(1)`, which
|
||||
* breaks simplification against numbers that came back from a numeric path.
|
||||
* Compare by value instead, with a tolerance for reals.
|
||||
*/
|
||||
export function numberEquals(lhs: MathNumber, rhs: MathNumber): boolean {
|
||||
const left = asFraction(lhs);
|
||||
const right = asFraction(rhs);
|
||||
if (left && right) return left[0] === right[0] && left[1] === right[1];
|
||||
const a = doubleValue(lhs);
|
||||
const b = doubleValue(rhs);
|
||||
if (a === b) return true;
|
||||
const scale = Math.max(Math.abs(a), Math.abs(b), 1);
|
||||
return Math.abs(a - b) <= 1e-12 * scale;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Display
|
||||
|
||||
/** Plain-text form for the glasses and for spoken readback. */
|
||||
export function describeNumber(value: MathNumber): string {
|
||||
switch (value.kind) {
|
||||
case "integer":
|
||||
return String(value.value);
|
||||
case "rational":
|
||||
return `${value.n}/${value.d}`;
|
||||
case "real": {
|
||||
const raw = value.value;
|
||||
if (Number.isNaN(raw)) return "NaN";
|
||||
if (raw === Math.round(raw) && Math.abs(raw) < 1e15) {
|
||||
return String(Math.round(raw));
|
||||
}
|
||||
// Trim to something a person can read aloud, without exponent notation
|
||||
// for ordinary magnitudes.
|
||||
if (Math.abs(raw) >= 1e-4 && Math.abs(raw) < 1e9) {
|
||||
let text = raw.toFixed(6);
|
||||
while (text.endsWith("0")) text = text.slice(0, -1);
|
||||
if (text.endsWith(".")) text = text.slice(0, -1);
|
||||
return text;
|
||||
}
|
||||
return formatG(raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Approximates C's %g: shortest of decimal/exponent form at 6 significant digits. */
|
||||
function formatG(value: number): string {
|
||||
if (value === 0) return "0";
|
||||
const exponent = Math.floor(Math.log10(Math.abs(value)));
|
||||
if (exponent >= -4 && exponent < 6) {
|
||||
const text = value.toPrecision(6);
|
||||
return trimTrailingZeros(text);
|
||||
}
|
||||
const mantissa = trimTrailingZeros((value / Math.pow(10, exponent)).toPrecision(6));
|
||||
const sign = exponent >= 0 ? "+" : "-";
|
||||
const padded = String(Math.abs(exponent)).padStart(2, "0");
|
||||
return `${mantissa}e${sign}${padded}`;
|
||||
}
|
||||
|
||||
function trimTrailingZeros(text: string): string {
|
||||
if (!text.includes(".")) return text;
|
||||
let result = text;
|
||||
while (result.endsWith("0")) result = result.slice(0, -1);
|
||||
if (result.endsWith(".")) result = result.slice(0, -1);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Thousands-separated integer. */
|
||||
export function formatInt(value: number): string {
|
||||
return Math.round(value).toLocaleString("en-US");
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
// Turns a spoken utterance into something the parser can read. ASR does not
|
||||
// emit `2x^2 + 3x - 5 = 0`; it emits "two x squared plus three x minus five
|
||||
// equals zero", and on a bad pass "2 x squared plus 3x minus 5 = 0". Every
|
||||
// rule here exists because one of those shapes has to land on the same tree.
|
||||
//
|
||||
// Deliberately NOT an LLM pass: a misheard equation should fail visibly at
|
||||
// the parser rather than be silently "corrected" into a different problem.
|
||||
|
||||
import { ALL_CONSTANTS, ALL_FUNCTIONS } from "./expression";
|
||||
|
||||
export function normalizeSpoken(raw: string): string {
|
||||
let text = raw
|
||||
.normalize("NFD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.toLowerCase()
|
||||
.replace(/’/g, "'");
|
||||
|
||||
text = stripTrailingDiscourse(text);
|
||||
text = stripPreamble(text);
|
||||
text = applyPhrases(text, FUNCTION_PHRASES);
|
||||
text = applyPhrases(text, RELATION_PHRASES);
|
||||
text = applyPhrases(text, OPERATOR_PHRASES);
|
||||
// Number words BEFORE powers: "two to the power of five" must become
|
||||
// "2 to the power of 5" first, or the power rule collapses it to
|
||||
// "two^five" and the parser sees two variables. Ordinals ("fifth") are
|
||||
// untouched by the number pass, so "to the fifth" still resolves after.
|
||||
text = applyNumberWords(text);
|
||||
text = applyPowerPhrases(text);
|
||||
text = applyFractionPhrases(text);
|
||||
text = applyPhrases(text, CONSTANT_PHRASES);
|
||||
text = collapseDigitGroups(text);
|
||||
text = insertImplicitMultiplication(text);
|
||||
|
||||
return text.replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Preamble
|
||||
|
||||
const TRAILING_PUNCTUATION = /^[ .,!?;:]+|[ .,!?;:]+$/g;
|
||||
|
||||
/**
|
||||
* Remove terminal speech-recognition filler that is not part of the problem.
|
||||
*
|
||||
* Always-on transcription commonly finalizes a valid equation together with
|
||||
* the next conversational beat (`3x plus 1. Thank you.`). Leaving that suffix
|
||||
* attached makes the deterministic parser reject otherwise complete
|
||||
* arithmetic and sends the calculator through its optional model-rewrite
|
||||
* fallback — turning an offline feature into an API-key error for users
|
||||
* without a cloud provider configured.
|
||||
*/
|
||||
export function stripTrailingDiscourse(text: string): string {
|
||||
const phrases = ["thank you", "thanks", "please", "okay", "ok"].sort((a, b) => b.length - a.length);
|
||||
let result = text.replace(TRAILING_PUNCTUATION, "");
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (const phrase of phrases) {
|
||||
if (result === phrase) {
|
||||
result = "";
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
const suffix = " " + phrase;
|
||||
if (result.endsWith(suffix)) {
|
||||
result = result.slice(0, -suffix.length).replace(TRAILING_PUNCTUATION, "");
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* "solve two x plus one equals five" → "two x plus one equals five". The
|
||||
* command word is consumed by the caller (it chooses the mode); what reaches
|
||||
* the parser must be only the mathematics.
|
||||
*/
|
||||
const PREAMBLES = [
|
||||
"can you solve",
|
||||
"please solve",
|
||||
"solve for me",
|
||||
"work out",
|
||||
"figure out",
|
||||
"calculate",
|
||||
"compute",
|
||||
"evaluate",
|
||||
"simplify",
|
||||
"solve",
|
||||
"what is",
|
||||
"whats",
|
||||
"what's",
|
||||
"how much is",
|
||||
"tell me",
|
||||
"the answer to",
|
||||
"the equation",
|
||||
"the expression",
|
||||
"graph",
|
||||
"plot",
|
||||
].sort((a, b) => b.length - a.length);
|
||||
|
||||
export function stripPreamble(text: string): string {
|
||||
let result = text.trim();
|
||||
let changed = true;
|
||||
// Loop: "can you solve what is 2 plus 2" has two stacked preambles.
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (const preamble of PREAMBLES) {
|
||||
if (result.startsWith(preamble + " ")) {
|
||||
result = result.slice(preamble.length + 1);
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Phrase tables
|
||||
|
||||
function escapeRegExp(text: string): string {
|
||||
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
/**
|
||||
* Longest-first replacement. "less than or equal to" must be tried before
|
||||
* "less than", or the tail becomes a stray "or equal to".
|
||||
*/
|
||||
function applyPhrases(text: string, phrases: readonly [string, string][]): string {
|
||||
let result = text;
|
||||
const sorted = [...phrases].sort((a, b) => b[0].length - a[0].length);
|
||||
for (const [phrase, replacement] of sorted) {
|
||||
result = result.replace(new RegExp(`\\b${escapeRegExp(phrase)}\\b`, "g"), replacement);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const RELATION_PHRASES: readonly [string, string][] = [
|
||||
["is less than or equal to", "<="],
|
||||
["less than or equal to", "<="],
|
||||
["is greater than or equal to", ">="],
|
||||
["greater than or equal to", ">="],
|
||||
["is at most", "<="],
|
||||
["at most", "<="],
|
||||
["is at least", ">="],
|
||||
["at least", ">="],
|
||||
["is less than", "<"],
|
||||
["less than", "<"],
|
||||
["is greater than", ">"],
|
||||
["greater than", ">"],
|
||||
["is equal to", "="],
|
||||
["equal to", "="],
|
||||
["equals", "="],
|
||||
["is the same as", "="],
|
||||
];
|
||||
|
||||
const OPERATOR_PHRASES: readonly [string, string][] = [
|
||||
["multiplied by", "*"],
|
||||
["times", "*"],
|
||||
["product of", "*"],
|
||||
["divided by", "/"],
|
||||
["over", "/"],
|
||||
["split by", "/"],
|
||||
["plus", "+"],
|
||||
["added to", "+"],
|
||||
["and then add", "+"],
|
||||
["minus", "-"],
|
||||
["subtract", "-"],
|
||||
["take away", "-"],
|
||||
["less", "-"],
|
||||
["modulo", "%"],
|
||||
["mod", "%"],
|
||||
["open paren", "("],
|
||||
["open parenthesis", "("],
|
||||
["open bracket", "("],
|
||||
["close paren", ")"],
|
||||
["close parenthesis", ")"],
|
||||
["close bracket", ")"],
|
||||
["negative", "-"],
|
||||
["minus sign", "-"],
|
||||
// "15 percent of 240" is 15/100 × 240. Mapping `percent` to the modulo
|
||||
// operator (which shares the glyph) turned every percentage question into a
|
||||
// remainder question — 15 % 240 = 15, silently wrong.
|
||||
["percent of", "/100 *"],
|
||||
["percent", "/100"],
|
||||
];
|
||||
|
||||
const FUNCTION_PHRASES: readonly [string, string][] = [
|
||||
["square root of", "sqrt"],
|
||||
["the square root of", "sqrt"],
|
||||
["root of", "sqrt"],
|
||||
["cube root of", "cbrt"],
|
||||
["natural log of", "ln"],
|
||||
["natural log", "ln"],
|
||||
["log base ten of", "log10"],
|
||||
["log base 10 of", "log10"],
|
||||
["log base two of", "log2"],
|
||||
["log base 2 of", "log2"],
|
||||
["log of", "log10"],
|
||||
["absolute value of", "abs"],
|
||||
["the absolute value of", "abs"],
|
||||
["sine of", "sin"],
|
||||
["cosine of", "cos"],
|
||||
["tangent of", "tan"],
|
||||
["arc sine of", "asin"],
|
||||
["arc cosine of", "acos"],
|
||||
["arc tangent of", "atan"],
|
||||
["inverse sine of", "asin"],
|
||||
["inverse cosine of", "acos"],
|
||||
["inverse tangent of", "atan"],
|
||||
["factorial of", "factorial"],
|
||||
["e to the power of", "exp"],
|
||||
];
|
||||
|
||||
const CONSTANT_PHRASES: readonly [string, string][] = [
|
||||
["pi", "pi"],
|
||||
["tau", "tau"],
|
||||
["euler's number", "e"],
|
||||
["eulers number", "e"],
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Powers
|
||||
|
||||
/** "x squared", "x to the power of three", "x cubed", "two to the fifth". */
|
||||
export function applyPowerPhrases(text: string): string {
|
||||
let result = text;
|
||||
const ordinalPowers: readonly [string, string][] = [
|
||||
["squared", "^2"],
|
||||
["cubed", "^3"],
|
||||
];
|
||||
for (const [phrase, replacement] of ordinalPowers) {
|
||||
result = result.replace(new RegExp(`\\s*\\b${phrase}\\b`, "g"), replacement);
|
||||
}
|
||||
// "to the power of N" / "to the N power" / "to the N"
|
||||
for (const pattern of [
|
||||
/\s*to the power of\s+/g,
|
||||
/\s*raised to the power of\s+/g,
|
||||
/\s*raised to\s+/g,
|
||||
/\s*to the\s+(?=[0-9])/g,
|
||||
]) {
|
||||
result = result.replace(pattern, "^");
|
||||
}
|
||||
// Ordinal exponents: "to the fifth" was normalised to "^fifth" above.
|
||||
const ordinals: readonly [string, string][] = [
|
||||
["first", "1"],
|
||||
["second", "2"],
|
||||
["third", "3"],
|
||||
["fourth", "4"],
|
||||
["fifth", "5"],
|
||||
["sixth", "6"],
|
||||
["seventh", "7"],
|
||||
["eighth", "8"],
|
||||
["ninth", "9"],
|
||||
["tenth", "10"],
|
||||
];
|
||||
for (const [word, digit] of ordinals) {
|
||||
result = result.replace(new RegExp(`\\^\\s*${word}(\\s+power)?\\b`, "g"), `^${digit}`);
|
||||
result = result.replace(new RegExp(`\\s*to the ${word}(\\s+power)?\\b`, "g"), `^${digit}`);
|
||||
}
|
||||
// Postfix "seven factorial" — the function table only covers the prefix
|
||||
// form ("factorial of seven").
|
||||
result = result.replace(/(\d+|\))\s*\bfactorial\b/g, "$1!");
|
||||
return result.replace(/\^\s+/g, "^");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fractions
|
||||
|
||||
/** "three over four", "two thirds", "one half". */
|
||||
export function applyFractionPhrases(text: string): string {
|
||||
let result = text;
|
||||
const denominators: readonly [string, number][] = [
|
||||
["halves", 2],
|
||||
["half", 2],
|
||||
["thirds", 3],
|
||||
["third", 3],
|
||||
["quarters", 4],
|
||||
["quarter", 4],
|
||||
["fourths", 4],
|
||||
["fourth", 4],
|
||||
["fifths", 5],
|
||||
["fifth", 5],
|
||||
["sixths", 6],
|
||||
["sixth", 6],
|
||||
["eighths", 8],
|
||||
["eighth", 8],
|
||||
["tenths", 10],
|
||||
["tenth", 10],
|
||||
];
|
||||
for (const [word, denominator] of denominators) {
|
||||
// Only when a number precedes it — "a third of the guests" is not
|
||||
// arithmetic, but "two thirds" is.
|
||||
result = result.replace(new RegExp(`\\b(\\d+)\\s+${word}\\b`, "g"), `($1/${denominator})`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Number words
|
||||
|
||||
const UNITS: readonly [string, number][] = [
|
||||
["zero", 0],
|
||||
["one", 1],
|
||||
["two", 2],
|
||||
["three", 3],
|
||||
["four", 4],
|
||||
["five", 5],
|
||||
["six", 6],
|
||||
["seven", 7],
|
||||
["eight", 8],
|
||||
["nine", 9],
|
||||
["ten", 10],
|
||||
["eleven", 11],
|
||||
["twelve", 12],
|
||||
["thirteen", 13],
|
||||
["fourteen", 14],
|
||||
["fifteen", 15],
|
||||
["sixteen", 16],
|
||||
["seventeen", 17],
|
||||
["eighteen", 18],
|
||||
["nineteen", 19],
|
||||
];
|
||||
|
||||
const TENS: readonly [string, number][] = [
|
||||
["twenty", 20],
|
||||
["thirty", 30],
|
||||
["forty", 40],
|
||||
["fifty", 50],
|
||||
["sixty", 60],
|
||||
["seventy", 70],
|
||||
["eighty", 80],
|
||||
["ninety", 90],
|
||||
];
|
||||
|
||||
/**
|
||||
* Fold English number words into digits, including compounds
|
||||
* ("twenty five" → 25, "three hundred" → 300, "two thousand ten" → 2010).
|
||||
*/
|
||||
export function applyNumberWords(text: string): string {
|
||||
const tokens = text.split(/\s+/).filter((token) => token.length > 0);
|
||||
const output: string[] = [];
|
||||
let index = 0;
|
||||
|
||||
while (index < tokens.length) {
|
||||
const [value, consumed] = parseNumberPhrase(tokens, index);
|
||||
if (value !== null && consumed > 0) {
|
||||
output.push(String(value));
|
||||
index += consumed;
|
||||
} else {
|
||||
output.push(tokens[index]!);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
return output.join(" ");
|
||||
}
|
||||
|
||||
/**
|
||||
* What the previous token was, which is what decides whether the next one
|
||||
* continues the same number or starts a new one. "twenty five" is 25;
|
||||
* "five five" is two numbers; "one hundred forty four" is 144.
|
||||
*/
|
||||
type NumberTokenKind = "none" | "unit" | "ten" | "hundred" | "scale";
|
||||
|
||||
/**
|
||||
* Greedy left-to-right accumulation with scale words. Returns [null, 0] when
|
||||
* the token at `start` does not begin a number phrase.
|
||||
*/
|
||||
function parseNumberPhrase(tokens: string[], start: number): [number | null, number] {
|
||||
let total = 0;
|
||||
let current = 0;
|
||||
let consumed = 0;
|
||||
let matchedAnything = false;
|
||||
let previous: NumberTokenKind = "none";
|
||||
|
||||
let index = start;
|
||||
while (index < tokens.length) {
|
||||
const token = tokens[index]!.replace(/^[,-]+|[,-]+$/g, "");
|
||||
const unit = UNITS.find(([word]) => word === token)?.[1];
|
||||
const ten = TENS.find(([word]) => word === token)?.[1];
|
||||
|
||||
if (unit !== undefined) {
|
||||
// A unit may follow a ten ("twenty five"), a hundred ("a hundred
|
||||
// four"), or a scale ("two thousand ten") — but not another unit, which
|
||||
// is two separate numbers.
|
||||
if (previous === "unit") break;
|
||||
current += unit;
|
||||
previous = "unit";
|
||||
} else if (ten !== undefined) {
|
||||
// After "hundred", `current` is non-zero; bailing there turned
|
||||
// "one hundred forty four" into "100 44".
|
||||
if (previous !== "none" && previous !== "hundred" && previous !== "scale") break;
|
||||
current += ten;
|
||||
previous = "ten";
|
||||
} else if (token === "hundred") {
|
||||
if (previous !== "unit" && previous !== "ten" && previous !== "none") break;
|
||||
if (current === 0) current = 1;
|
||||
current *= 100;
|
||||
previous = "hundred";
|
||||
} else if (token === "thousand" || token === "million") {
|
||||
const scale = token === "thousand" ? 1_000 : 1_000_000;
|
||||
if (current === 0 && total === 0) current = 1;
|
||||
total += current * scale;
|
||||
current = 0;
|
||||
previous = "scale";
|
||||
} else if (token === "and" && matchedAnything && index + 1 < tokens.length && isNumberWord(tokens[index + 1]!)) {
|
||||
// "three hundred and five" — but a bare "and" elsewhere is not part of
|
||||
// the number.
|
||||
index += 1;
|
||||
consumed += 1;
|
||||
continue;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
matchedAnything = true;
|
||||
index += 1;
|
||||
consumed += 1;
|
||||
}
|
||||
|
||||
if (!matchedAnything) return [null, 0];
|
||||
return [total + current, consumed];
|
||||
}
|
||||
|
||||
function isNumberWord(token: string): boolean {
|
||||
const cleaned = token.replace(/^[,-]+|[,-]+$/g, "");
|
||||
return (
|
||||
UNITS.some(([word]) => word === cleaned) ||
|
||||
TENS.some(([word]) => word === cleaned) ||
|
||||
["hundred", "thousand", "million"].includes(cleaned)
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Digit groups
|
||||
|
||||
/**
|
||||
* ASR renders a dictated "four hundred and five" that it already digitised as
|
||||
* "4 05" or "400 5". The first is a spacing artefact and joins; the second is
|
||||
* genuinely ambiguous and is left alone.
|
||||
*/
|
||||
export function collapseDigitGroups(text: string): string {
|
||||
return text.replace(/\b(\d+)\s+(0\d+)\b/g, "$1$2");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Implicit multiplication
|
||||
|
||||
/**
|
||||
* Names the implicit-multiplication repair must not split.
|
||||
*/
|
||||
export const RESERVED_WORDS: readonly string[] = [...ALL_FUNCTIONS, ...ALL_CONSTANTS, "log", "sqrt"];
|
||||
|
||||
/**
|
||||
* The subset that is CALLED, so a star between the name and its opening paren
|
||||
* is an artefact of the implicit-multiplication rules rather than a real
|
||||
* operator. Constants are excluded deliberately: `pi*(r+1)` must keep its
|
||||
* multiplication.
|
||||
*/
|
||||
export const RESERVED_FUNCTION_NAMES: readonly string[] = [...ALL_FUNCTIONS, "log", "sqrt"];
|
||||
|
||||
/**
|
||||
* "2x" and "3(x+1)" and "2 x" all mean multiplication. Inserting the `*` here
|
||||
* rather than in the parser keeps the grammar unambiguous, and makes the
|
||||
* normalised string something a wearer can read back and verify.
|
||||
*/
|
||||
export function insertImplicitMultiplication(text: string): string {
|
||||
let result = text;
|
||||
const rules: readonly [RegExp, string][] = [
|
||||
// number followed by a letter or an opening paren: 2x, 2(
|
||||
[/(\d)\s*([a-z(])/g, "$1*$2"],
|
||||
// closing paren followed by a number, letter, or paren: )x, )2, )(
|
||||
[/(\))\s*([a-z0-9(])/g, "$1*$2"],
|
||||
// a single-letter variable immediately followed by a paren
|
||||
[/(?<![a-z])([a-z])\s*(\()/g, "$1*$2"],
|
||||
];
|
||||
for (const [pattern, replacement] of rules) {
|
||||
result = result.replace(pattern, replacement);
|
||||
}
|
||||
// The rules above will happily turn `sqrt(x)` into `sqr*t*(x)` and `2*x`
|
||||
// inside a known function name; repair the known names.
|
||||
//
|
||||
// The optional star belongs strictly BETWEEN the characters of a word.
|
||||
// Appending one after the final character too (`p\*?i\*?` for `pi`) made
|
||||
// the repair swallow a legitimate operator that merely FOLLOWED the word:
|
||||
// `2*pi*r` became `2*pir`, which then parsed as three unbound variables and
|
||||
// silently produced a different answer.
|
||||
//
|
||||
// A function name immediately before its opening paren is the one
|
||||
// exception: the rules above rewrite `sqrt(x)` to `sqr*t*(x)`, so that
|
||||
// trailing star really is spurious. A CONSTANT is never called, so a star
|
||||
// after `pi` or `e` is always a real multiplication — `pi*(r+1)` has to
|
||||
// keep it. Run the narrower function rule first, then the general
|
||||
// between-characters repair over everything.
|
||||
for (const name of RESERVED_FUNCTION_NAMES) {
|
||||
if (name.length <= 1) continue;
|
||||
const pattern = name.split("").join("\\*?") + "\\*?(?=\\()";
|
||||
result = result.replace(new RegExp(pattern, "g"), name);
|
||||
}
|
||||
for (const name of RESERVED_WORDS) {
|
||||
// A single-character constant such as `e` has nothing to repair between
|
||||
// characters, so it is skipped entirely.
|
||||
if (name.length <= 1) continue;
|
||||
const pattern = name.split("").join("\\*?");
|
||||
result = result.replace(new RegExp(pattern, "g"), name);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
// Integer arithmetic: primality, factorisation, modular arithmetic, and the
|
||||
// classic sequences. Modular products use BigInt internally — `(a*b) % m`
|
||||
// in floats loses exactness long before the moduli a cryptography-flavoured
|
||||
// question uses.
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Primality
|
||||
|
||||
const SMALL_PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];
|
||||
|
||||
/**
|
||||
* Deterministic Miller-Rabin. The witness set below is *proven* to decide
|
||||
* primality for every 64-bit integer, so this is exact rather than
|
||||
* probabilistic.
|
||||
*/
|
||||
export function isPrime(value: number): boolean {
|
||||
if (!Number.isSafeInteger(value) || value < 2) return false;
|
||||
for (const small of SMALL_PRIMES) {
|
||||
if (value === small) return true;
|
||||
if (value % small === 0) return false;
|
||||
}
|
||||
let d = BigInt(value - 1);
|
||||
let r = 0;
|
||||
while (d % 2n === 0n) {
|
||||
d /= 2n;
|
||||
r += 1;
|
||||
}
|
||||
|
||||
const n = BigInt(value);
|
||||
for (const witness of SMALL_PRIMES) {
|
||||
let x = modularPowerBig(BigInt(witness), d, n);
|
||||
if (x === 1n || x === n - 1n) continue;
|
||||
let composite = true;
|
||||
for (let step = 0; step < r - 1; step++) {
|
||||
x = (x * x) % n;
|
||||
if (x === n - 1n) {
|
||||
composite = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (composite) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The next prime at or above `value`, or null when the search is unreasonable. */
|
||||
export function nextPrime(after: number): number | null {
|
||||
let candidate = Math.max(2, after + 1);
|
||||
// Bounded: a caller asking near the integer ceiling should get null, not a hang.
|
||||
while (Number.isSafeInteger(candidate) && candidate - after < 1_000_000) {
|
||||
if (isPrime(candidate)) return candidate;
|
||||
candidate += 1;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function primesUpTo(limit: number): number[] {
|
||||
if (limit < 2) return [];
|
||||
const sieve = new Uint8Array(limit + 1).fill(1);
|
||||
sieve[0] = 0;
|
||||
sieve[1] = 0;
|
||||
for (let candidate = 2; candidate * candidate <= limit; candidate++) {
|
||||
if (!sieve[candidate]) continue;
|
||||
for (let multiple = candidate * candidate; multiple <= limit; multiple += candidate) {
|
||||
sieve[multiple] = 0;
|
||||
}
|
||||
}
|
||||
const result: number[] = [];
|
||||
for (let value = 2; value <= limit; value++) {
|
||||
if (sieve[value]) result.push(value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Factorisation
|
||||
|
||||
export type PrimeFactor = { prime: number; exponent: number };
|
||||
|
||||
/**
|
||||
* Trial division by small primes, then Pollard's rho for the rest.
|
||||
*
|
||||
* Trial division alone is fine to ~10⁷ and hopeless beyond; rho handles
|
||||
* semiprimes with large factors, which is exactly the shape that makes a
|
||||
* naive factoriser appear to hang.
|
||||
*/
|
||||
export function factorize(value: number): PrimeFactor[] {
|
||||
if (value === 0 || !Number.isSafeInteger(value)) return [];
|
||||
let remaining = Math.abs(value);
|
||||
const counts = new Map<number, number>();
|
||||
|
||||
for (const prime of primesUpTo(100_000)) {
|
||||
if (prime * prime > remaining) break;
|
||||
while (remaining % prime === 0) {
|
||||
counts.set(prime, (counts.get(prime) ?? 0) + 1);
|
||||
remaining /= prime;
|
||||
}
|
||||
}
|
||||
if (remaining > 1) {
|
||||
for (const factor of pollardFactorize(remaining)) {
|
||||
counts.set(factor, (counts.get(factor) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
return [...counts.keys()].sort((a, b) => a - b).map((prime) => ({ prime, exponent: counts.get(prime)! }));
|
||||
}
|
||||
|
||||
function pollardFactorize(value: number): number[] {
|
||||
if (value === 1) return [];
|
||||
if (isPrime(value)) return [value];
|
||||
const divisor = pollardRho(value);
|
||||
if (divisor === null) return [value];
|
||||
return [...pollardFactorize(divisor), ...pollardFactorize(value / divisor)];
|
||||
}
|
||||
|
||||
function pollardRho(n: number): number | null {
|
||||
if (n % 2 === 0) return 2;
|
||||
const big = BigInt(n);
|
||||
// Deterministic sequence of offsets rather than a random one: the same
|
||||
// input must factor the same way every run, or a test is a coin flip.
|
||||
for (let offset = 1n; offset <= 40n; offset++) {
|
||||
let x = 2n;
|
||||
let y = 2n;
|
||||
let divisor = 1n;
|
||||
while (divisor === 1n) {
|
||||
x = (x * x + offset) % big;
|
||||
y = (y * y + offset) % big;
|
||||
y = (y * y + offset) % big;
|
||||
divisor = gcdBig(absBig(x - y), big);
|
||||
}
|
||||
if (divisor !== big) return Number(divisor);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function absBig(value: bigint): bigint {
|
||||
return value < 0n ? -value : value;
|
||||
}
|
||||
|
||||
function gcdBig(a: bigint, b: bigint): bigint {
|
||||
let x = a;
|
||||
let y = b;
|
||||
while (y !== 0n) {
|
||||
const next = x % y;
|
||||
x = y;
|
||||
y = next;
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
export function divisorsOf(value: number): number[] {
|
||||
const magnitude = Math.abs(value);
|
||||
if (magnitude <= 0) return [];
|
||||
let result: number[] = [1];
|
||||
for (const factor of factorize(magnitude)) {
|
||||
const expanded: number[] = [];
|
||||
let power = 1;
|
||||
for (let step = 0; step <= factor.exponent; step++) {
|
||||
expanded.push(...result.map((existing) => existing * power));
|
||||
power *= factor.prime;
|
||||
}
|
||||
result = expanded;
|
||||
}
|
||||
return result.sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
/**
|
||||
* σ(n) and τ(n) come free from the factorisation and are what "perfect
|
||||
* number" and "abundant" questions actually need.
|
||||
*/
|
||||
export function divisorSum(value: number): number {
|
||||
return factorize(Math.abs(value)).reduce((total, factor) => {
|
||||
let term = 1;
|
||||
let power = 1;
|
||||
for (let step = 0; step < factor.exponent; step++) {
|
||||
power *= factor.prime;
|
||||
term += power;
|
||||
}
|
||||
return total * term;
|
||||
}, 1);
|
||||
}
|
||||
|
||||
export function divisorCount(value: number): number {
|
||||
return factorize(Math.abs(value)).reduce((total, factor) => total * (factor.exponent + 1), 1);
|
||||
}
|
||||
|
||||
/** Euler's totient. */
|
||||
export function totient(value: number): number {
|
||||
if (value <= 0) return 0;
|
||||
let result = value;
|
||||
for (const factor of factorize(value)) {
|
||||
result = (result / factor.prime) * (factor.prime - 1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GCD / LCM
|
||||
|
||||
export function greatestCommonDivisor(a: number, b: number): number {
|
||||
let x = Math.abs(a);
|
||||
let y = Math.abs(b);
|
||||
while (y !== 0) {
|
||||
const next = x % y;
|
||||
x = y;
|
||||
y = next;
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
export function leastCommonMultiple(a: number, b: number): number {
|
||||
if (a === 0 || b === 0) return 0;
|
||||
return Math.abs((a / greatestCommonDivisor(a, b)) * b);
|
||||
}
|
||||
|
||||
/** Extended Euclid: returns `[gcd, x, y]` with `ax + by = gcd`. */
|
||||
export function extendedGCD(a: number, b: number): [number, number, number] {
|
||||
if (b === 0) return [Math.abs(a), a < 0 ? -1 : 1, 0];
|
||||
const [gcd, x, y] = extendedGCD(b, a % b);
|
||||
return [gcd, y, x - Math.floor(a / b) * y];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Modular arithmetic
|
||||
|
||||
/**
|
||||
* Always non-negative, unlike `%`. JavaScript's `%` on a negative left
|
||||
* operand returns a negative remainder, which is wrong for every modular use
|
||||
* here.
|
||||
*/
|
||||
export function mod(value: number, modulus: number): number {
|
||||
if (modulus === 0) return 0;
|
||||
const remainder = value % modulus;
|
||||
return remainder < 0 ? remainder + Math.abs(modulus) : remainder;
|
||||
}
|
||||
|
||||
function modularPowerBig(base: bigint, exponent: bigint, modulus: bigint): bigint {
|
||||
let result = 1n;
|
||||
let b = base % modulus;
|
||||
if (b < 0n) b += modulus;
|
||||
let e = exponent;
|
||||
while (e > 0n) {
|
||||
if (e & 1n) result = (result * b) % modulus;
|
||||
b = (b * b) % modulus;
|
||||
e >>= 1n;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function modularPower(base: number, exponent: number, modulus: number): number {
|
||||
if (modulus <= 1) return 0;
|
||||
if (exponent < 0) {
|
||||
const inverse = modularInverse(base, modulus);
|
||||
if (inverse === null) return 0;
|
||||
return modularPower(inverse, -exponent, modulus);
|
||||
}
|
||||
return Number(modularPowerBig(BigInt(base), BigInt(exponent), BigInt(modulus)));
|
||||
}
|
||||
|
||||
/**
|
||||
* null when `value` and `modulus` are not coprime — an inverse genuinely
|
||||
* does not exist, and returning 0 would look like an answer.
|
||||
*/
|
||||
export function modularInverse(value: number, modulus: number): number | null {
|
||||
if (modulus <= 1) return null;
|
||||
const [gcd, x] = extendedGCD(mod(value, modulus), modulus);
|
||||
if (gcd !== 1) return null;
|
||||
return mod(x, modulus);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sequences
|
||||
|
||||
/** null past fib(78) — the largest that stays an exact double. */
|
||||
export function fibonacci(n: number): number | null {
|
||||
if (n < 0) return null;
|
||||
if (n === 0) return 0;
|
||||
let a = 0;
|
||||
let b = 1; // fib(0), fib(1)
|
||||
// Stop one short and return `b`, so a representable answer is never
|
||||
// reported as overflow by computing fib(n+1) as a side effect.
|
||||
for (let step = 1; step < n; step++) {
|
||||
const next = a + b;
|
||||
if (!Number.isSafeInteger(next)) return null;
|
||||
a = b;
|
||||
b = next;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
export function binomial(n: number, k: number): number | null {
|
||||
if (n < 0 || k < 0 || k > n) return null;
|
||||
const kk = Math.min(k, n - k);
|
||||
let result = 1;
|
||||
for (let step = 0; step < kk; step++) {
|
||||
// Multiply then divide keeps every intermediate an integer, and the
|
||||
// division is always exact at this point.
|
||||
const product = result * (n - step);
|
||||
if (!Number.isSafeInteger(product)) return null;
|
||||
result = product / (step + 1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Digit sum, digital root, and palindrome are the recreational-maths staples
|
||||
* a spoken question actually reaches for.
|
||||
*/
|
||||
export function digitSum(value: number): number {
|
||||
let remaining = Math.abs(value);
|
||||
let total = 0;
|
||||
while (remaining > 0) {
|
||||
total += remaining % 10;
|
||||
remaining = Math.floor(remaining / 10);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
export function digitalRoot(value: number): number {
|
||||
const magnitude = Math.abs(value);
|
||||
return magnitude === 0 ? 0 : 1 + ((magnitude - 1) % 9);
|
||||
}
|
||||
|
||||
export function isPalindrome(value: number): boolean {
|
||||
const text = String(Math.abs(value));
|
||||
return text === [...text].reverse().join("");
|
||||
}
|
||||
|
||||
export function isPerfect(value: number): boolean {
|
||||
return value > 1 && divisorSum(value) - value === value;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Reporting
|
||||
|
||||
/** A full dossier on one integer, which is what "tell me about 5,040" means. */
|
||||
export type IntegerReport = {
|
||||
value: number;
|
||||
isPrime: boolean;
|
||||
factorization: PrimeFactor[];
|
||||
divisorCount: number;
|
||||
divisorSum: number;
|
||||
totient: number;
|
||||
digitSum: number;
|
||||
digitalRoot: number;
|
||||
isPerfect: boolean;
|
||||
isPalindrome: boolean;
|
||||
};
|
||||
|
||||
export function factorizationText(report: IntegerReport): string {
|
||||
if (report.factorization.length === 0) return String(report.value);
|
||||
return report.factorization
|
||||
.map((factor) => (factor.exponent === 1 ? `${factor.prime}` : `${factor.prime}^${factor.exponent}`))
|
||||
.join(" × ");
|
||||
}
|
||||
|
||||
export function integerReport(value: number): IntegerReport {
|
||||
return {
|
||||
value,
|
||||
isPrime: isPrime(value),
|
||||
factorization: factorize(value),
|
||||
divisorCount: divisorCount(value),
|
||||
divisorSum: divisorSum(value),
|
||||
totient: totient(Math.abs(value)),
|
||||
digitSum: digitSum(value),
|
||||
digitalRoot: digitalRoot(value),
|
||||
isPerfect: isPerfect(value),
|
||||
isPalindrome: isPalindrome(value),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
// Recursive-descent parser over the token stream.
|
||||
//
|
||||
// Grammar, loosest to tightest:
|
||||
//
|
||||
// relation := sum (relop sum)?
|
||||
// sum := product (('+' | '-') product)*
|
||||
// product := unary (('*' | '/' | '%') unary)*
|
||||
// unary := ('-' | '+') unary | power
|
||||
// power := postfix ('^' unary)? -- right associative
|
||||
// postfix := primary '!'*
|
||||
// primary := number | constant | variable | call | '(' relation ')' | '|' sum '|'
|
||||
//
|
||||
// `^` binds tighter than unary minus on its left, so `-x^2` is `-(x^2)` — the
|
||||
// convention every textbook and every other calculator uses. Getting that
|
||||
// backwards silently changes the answer, so it has a test.
|
||||
|
||||
import { type MathToken, MathParseError, tokenize } from "./lexer";
|
||||
import {
|
||||
type MathExpression,
|
||||
type MathFunction,
|
||||
type MathConstant,
|
||||
ALL_CONSTANTS,
|
||||
ALL_FUNCTIONS,
|
||||
addExpr,
|
||||
constant,
|
||||
divideExpr,
|
||||
fn,
|
||||
int,
|
||||
multiplyExpr,
|
||||
negate,
|
||||
num,
|
||||
powerExpr,
|
||||
relation,
|
||||
subtractExpr,
|
||||
variable,
|
||||
} from "./expression";
|
||||
import { describeNumber } from "./math-number";
|
||||
import { normalizeSpoken } from "./normalizer";
|
||||
|
||||
/**
|
||||
* Guards against a pathological input recursing until the stack dies. A crash
|
||||
* on the wearer's face is the worst possible failure mode.
|
||||
*/
|
||||
const MAXIMUM_DEPTH = 64;
|
||||
|
||||
export function parse(input: string): MathExpression {
|
||||
const parser = new Parser(tokenize(input), input);
|
||||
const expression = parser.parseRelation();
|
||||
parser.expectEnd();
|
||||
return expression;
|
||||
}
|
||||
|
||||
/** Parse text that came from speech: normalise first, then parse. */
|
||||
export function parseSpoken(spoken: string): MathExpression {
|
||||
const normalized = normalizeSpoken(spoken);
|
||||
if (!normalized) throw new MathParseError({ kind: "emptyInput" }, spoken);
|
||||
try {
|
||||
return parse(normalized);
|
||||
} catch (error) {
|
||||
// Report against what the user SAID, not against the normalised form they
|
||||
// never typed — otherwise the error quotes machine output.
|
||||
if (error instanceof MathParseError) {
|
||||
throw new MathParseError(error.errorKind, spoken);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
class Parser {
|
||||
private index = 0;
|
||||
private depth = 0;
|
||||
|
||||
constructor(
|
||||
private readonly tokens: MathToken[],
|
||||
private readonly source: string,
|
||||
) {}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Grammar
|
||||
|
||||
parseRelation(): MathExpression {
|
||||
const lhs = this.parseSum();
|
||||
const token = this.peek();
|
||||
if (!token || token.type !== "relation") return lhs;
|
||||
this.advance();
|
||||
const rhs = this.parseSum();
|
||||
// A chained relation ("1 < x < 5") is a real thing people say, but it is
|
||||
// not a single relation node; rejecting it beats silently keeping only
|
||||
// half of the constraint.
|
||||
if (this.peek()?.type === "relation") {
|
||||
throw new MathParseError({ kind: "unexpectedToken", token: "chained comparison" }, this.source);
|
||||
}
|
||||
return relation(token.relation, lhs, rhs);
|
||||
}
|
||||
|
||||
private parseSum(): MathExpression {
|
||||
const terms = [this.parseProduct()];
|
||||
for (;;) {
|
||||
const token = this.peek();
|
||||
if (token?.type === "plus") {
|
||||
this.advance();
|
||||
terms.push(this.parseProduct());
|
||||
} else if (token?.type === "minus") {
|
||||
this.advance();
|
||||
terms.push(negate(this.parseProduct()));
|
||||
} else {
|
||||
return terms.length === 1 ? terms[0]! : addExpr(terms);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private parseProduct(): MathExpression {
|
||||
let factors = [this.parseUnary()];
|
||||
for (;;) {
|
||||
const token = this.peek();
|
||||
if (token?.type === "star") {
|
||||
this.advance();
|
||||
factors.push(this.parseUnary());
|
||||
} else if (token?.type === "slash") {
|
||||
this.advance();
|
||||
factors.push(powerExpr(this.parseUnary(), int(-1)));
|
||||
} else if (token?.type === "percent") {
|
||||
this.advance();
|
||||
const divisor = this.parseUnary();
|
||||
const dividend = factors.length === 1 ? factors[0]! : multiplyExpr(factors);
|
||||
// a mod b == a - b * floor(a / b). Expressed in terms the rest of the
|
||||
// engine already handles, so modulo needs no special case in the
|
||||
// evaluator, simplifier, or differentiator.
|
||||
const quotient = fn("floor", [divideExpr(dividend, divisor)]);
|
||||
factors = [subtractExpr(dividend, multiplyExpr([divisor, quotient]))];
|
||||
} else {
|
||||
return factors.length === 1 ? factors[0]! : multiplyExpr(factors);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private parseUnary(): MathExpression {
|
||||
const token = this.peek();
|
||||
if (token?.type === "minus") {
|
||||
this.advance();
|
||||
return negate(this.parseUnary());
|
||||
}
|
||||
if (token?.type === "plus") {
|
||||
this.advance();
|
||||
return this.parseUnary();
|
||||
}
|
||||
return this.parsePower();
|
||||
}
|
||||
|
||||
private parsePower(): MathExpression {
|
||||
const base = this.parsePostfix();
|
||||
if (this.peek()?.type !== "caret") return base;
|
||||
this.advance();
|
||||
// Right-associative AND allows a unary exponent: 2^-1, 2^3^2 = 2^(3^2).
|
||||
const exponent = this.parseUnary();
|
||||
return powerExpr(base, exponent);
|
||||
}
|
||||
|
||||
private parsePostfix(): MathExpression {
|
||||
let expression = this.parsePrimary();
|
||||
while (this.peek()?.type === "bang") {
|
||||
this.advance();
|
||||
expression = fn("factorial", [expression]);
|
||||
}
|
||||
return expression;
|
||||
}
|
||||
|
||||
private parsePrimary(): MathExpression {
|
||||
this.depth += 1;
|
||||
try {
|
||||
if (this.depth >= MAXIMUM_DEPTH) {
|
||||
throw new MathParseError({ kind: "tooComplex" }, this.source);
|
||||
}
|
||||
const token = this.peek();
|
||||
if (!token) throw new MathParseError({ kind: "unexpectedEnd" }, this.source);
|
||||
|
||||
switch (token.type) {
|
||||
case "number":
|
||||
this.advance();
|
||||
return num(token.value);
|
||||
|
||||
case "identifier":
|
||||
this.advance();
|
||||
return this.parseIdentifier(token.name);
|
||||
|
||||
case "leftParen": {
|
||||
this.advance();
|
||||
const inner = this.parseRelation();
|
||||
this.expect("rightParen");
|
||||
return inner;
|
||||
}
|
||||
|
||||
case "pipe": {
|
||||
// |x| — absolute value. The closing pipe is unambiguous because a
|
||||
// bare `|` is not an operator anywhere else in the grammar.
|
||||
this.advance();
|
||||
const inner = this.parseSum();
|
||||
this.expect("pipe");
|
||||
return fn("abs", [inner]);
|
||||
}
|
||||
|
||||
case "minus":
|
||||
case "plus":
|
||||
return this.parseUnary();
|
||||
|
||||
default:
|
||||
throw new MathParseError({ kind: "unexpectedToken", token: describeToken(token) }, this.source);
|
||||
}
|
||||
} finally {
|
||||
this.depth -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
private parseIdentifier(name: string): MathExpression {
|
||||
const lowered = name.toLowerCase();
|
||||
|
||||
if ((ALL_CONSTANTS as readonly string[]).includes(lowered)) {
|
||||
return constant(lowered as MathConstant);
|
||||
}
|
||||
// `log` with no base means base 10 in ordinary speech, not natural log.
|
||||
const resolved = lowered === "log" ? "log10" : lowered;
|
||||
if ((ALL_FUNCTIONS as readonly string[]).includes(resolved)) {
|
||||
const functionName = resolved as MathFunction;
|
||||
// Both `sin(x)` and the spoken-normalised `sin x` must parse.
|
||||
if (this.peek()?.type === "leftParen") {
|
||||
this.advance();
|
||||
const args = [this.parseSum()];
|
||||
while (this.peek()?.type === "comma") {
|
||||
this.advance();
|
||||
args.push(this.parseSum());
|
||||
}
|
||||
this.expect("rightParen");
|
||||
return fn(functionName, args);
|
||||
}
|
||||
const argument = this.parsePower();
|
||||
return fn(functionName, [argument]);
|
||||
}
|
||||
|
||||
// A run of single letters from the normaliser ("xy") is a product of
|
||||
// variables, not one variable named "xy". Multi-letter names are only
|
||||
// honoured when the caller typed them with an underscore or a digit.
|
||||
if (lowered.length > 1 && !lowered.includes("_") && !/\d/.test(lowered)) {
|
||||
const factors = lowered.split("").map((letter) => variable(letter));
|
||||
return multiplyExpr(factors);
|
||||
}
|
||||
return variable(lowered);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Token plumbing
|
||||
|
||||
private peek(): MathToken | null {
|
||||
return this.index < this.tokens.length ? this.tokens[this.index]! : null;
|
||||
}
|
||||
|
||||
private advance(): void {
|
||||
this.index += 1;
|
||||
}
|
||||
|
||||
private expect(type: MathToken["type"]): void {
|
||||
const actual = this.peek();
|
||||
if (!actual) {
|
||||
throw new MathParseError(
|
||||
type === "rightParen" ? { kind: "unbalancedParenthesis" } : { kind: "unexpectedEnd" },
|
||||
this.source,
|
||||
);
|
||||
}
|
||||
if (actual.type !== type) {
|
||||
throw new MathParseError(
|
||||
type === "rightParen"
|
||||
? { kind: "unbalancedParenthesis" }
|
||||
: { kind: "unexpectedToken", token: describeToken(actual) },
|
||||
this.source,
|
||||
);
|
||||
}
|
||||
this.advance();
|
||||
}
|
||||
|
||||
expectEnd(): void {
|
||||
if (this.index < this.tokens.length) {
|
||||
throw new MathParseError(
|
||||
{ kind: "unexpectedToken", token: describeToken(this.tokens[this.index]!) },
|
||||
this.source,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function describeToken(token: MathToken): string {
|
||||
switch (token.type) {
|
||||
case "number":
|
||||
return describeNumber(token.value);
|
||||
case "identifier":
|
||||
return token.name;
|
||||
case "plus":
|
||||
return "+";
|
||||
case "minus":
|
||||
return "-";
|
||||
case "star":
|
||||
return "*";
|
||||
case "slash":
|
||||
return "/";
|
||||
case "percent":
|
||||
return "%";
|
||||
case "caret":
|
||||
return "^";
|
||||
case "bang":
|
||||
return "!";
|
||||
case "leftParen":
|
||||
return "(";
|
||||
case "rightParen":
|
||||
return ")";
|
||||
case "pipe":
|
||||
return "|";
|
||||
case "comma":
|
||||
return ",";
|
||||
case "relation":
|
||||
return token.relation;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
// Samples an expression into drawable graph data: segments, viewport,
|
||||
// roots, and extrema.
|
||||
|
||||
import { type MathExpression, subtractExpr, variablesOf } from "./expression";
|
||||
import { evaluateValue } from "./evaluator";
|
||||
import { simplify } from "./simplifier";
|
||||
import { Polynomial } from "./polynomial";
|
||||
import { numericRoots } from "./solver";
|
||||
import { fromDecimal, describeNumber } from "./math-number";
|
||||
import { plain } from "./text-renderer";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plot model
|
||||
|
||||
export type GraphViewport = {
|
||||
xMin: number;
|
||||
xMax: number;
|
||||
yMin: number;
|
||||
yMax: number;
|
||||
};
|
||||
|
||||
export const STANDARD_VIEWPORT: GraphViewport = { xMin: -10, xMax: 10, yMin: -10, yMax: 10 };
|
||||
|
||||
export function viewportContainsY(viewport: GraphViewport, y: number): boolean {
|
||||
return y >= viewport.yMin && y <= viewport.yMax;
|
||||
}
|
||||
|
||||
export type GraphPoint = { x: number; y: number };
|
||||
|
||||
/**
|
||||
* One continuous run of the curve. A function with a pole produces several,
|
||||
* so the renderer can lift the pen instead of drawing a vertical line through
|
||||
* the asymptote — which is the single most recognisable "bad graphing app"
|
||||
* artefact.
|
||||
*/
|
||||
export type GraphSegment = { points: GraphPoint[] };
|
||||
|
||||
export type GraphMarkerKind = "root" | "yIntercept" | "extremum" | "intersection";
|
||||
|
||||
export type GraphMarker = {
|
||||
kind: GraphMarkerKind;
|
||||
point: GraphPoint;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export type GraphPlot = {
|
||||
expression: MathExpression;
|
||||
variable: string;
|
||||
segments: GraphSegment[];
|
||||
markers: GraphMarker[];
|
||||
label: string;
|
||||
};
|
||||
|
||||
export type GraphAxis = { ticks: number[]; step: number };
|
||||
|
||||
export type Graph = {
|
||||
plots: GraphPlot[];
|
||||
viewport: GraphViewport;
|
||||
xAxis: GraphAxis;
|
||||
yAxis: GraphAxis;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plotter
|
||||
|
||||
/**
|
||||
* Sample count. Matched to the glasses viewport width times a small factor:
|
||||
* enough that a curve looks smooth after projection, few enough that plotting
|
||||
* stays imperceptible on a phone.
|
||||
*/
|
||||
export const DEFAULT_SAMPLE_COUNT = 1_200;
|
||||
|
||||
/** Values beyond this are treated as a pole rather than a steep slope. */
|
||||
const POLE_THRESHOLD = 1e7;
|
||||
|
||||
export function plot(
|
||||
expressions: MathExpression[],
|
||||
options: {
|
||||
variable?: string;
|
||||
viewport?: GraphViewport;
|
||||
usesDegrees?: boolean;
|
||||
sampleCount?: number;
|
||||
} = {},
|
||||
): Graph {
|
||||
const usesDegrees = options.usesDegrees ?? false;
|
||||
const sampleCount = options.sampleCount ?? DEFAULT_SAMPLE_COUNT;
|
||||
const variable =
|
||||
options.variable ??
|
||||
expressions.map((expression) => variablesOf(expression)[0]).find((name) => name !== undefined) ??
|
||||
"x";
|
||||
|
||||
// Autoscale y from the data when the caller did not pin a viewport, but
|
||||
// keep x at the requested (or standard) window — rescaling both makes a
|
||||
// graph that never matches what the user asked to see.
|
||||
const xWindow = options.viewport ?? STANDARD_VIEWPORT;
|
||||
const plots: GraphPlot[] = [];
|
||||
const allY: number[] = [];
|
||||
|
||||
for (const expression of expressions) {
|
||||
const body = functionBody(expression);
|
||||
const sampled = sample(body, variable, xWindow.xMin, xWindow.xMax, sampleCount, usesDegrees);
|
||||
for (const segment of sampled) {
|
||||
for (const point of segment.points) allY.push(point.y);
|
||||
}
|
||||
plots.push({
|
||||
expression: body,
|
||||
variable,
|
||||
segments: sampled,
|
||||
markers: markers(body, variable, xWindow.xMin, xWindow.xMax),
|
||||
label: plain(body),
|
||||
});
|
||||
}
|
||||
|
||||
const viewport = options.viewport ?? autoscale(xWindow, allY);
|
||||
const clipped = plots.map((entry) => ({
|
||||
expression: entry.expression,
|
||||
variable: entry.variable,
|
||||
segments: clip(entry.segments, viewport),
|
||||
markers: entry.markers.filter((marker) => viewportContainsY(viewport, marker.point.y)),
|
||||
label: entry.label,
|
||||
}));
|
||||
|
||||
return {
|
||||
plots: clipped,
|
||||
viewport,
|
||||
xAxis: axis(viewport.xMin, viewport.xMax),
|
||||
yAxis: axis(viewport.yMin, viewport.yMax),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* `y = x^2 + 1` and `x^2 + 1` should plot the same curve, and `x^2 + y = 1`
|
||||
* should plot `y = 1 - x^2` where that is easy to see.
|
||||
*/
|
||||
export function functionBody(expression: MathExpression): MathExpression {
|
||||
if (expression.type !== "relation") return expression;
|
||||
if (expression.lhs.type === "variable" && expression.lhs.name === "y") return expression.rhs;
|
||||
if (expression.rhs.type === "variable" && expression.rhs.name === "y") return expression.lhs;
|
||||
// Otherwise plot the difference, whose zero set is the relation — the
|
||||
// honest generalisation, and it makes an implicit curve's roots visible on
|
||||
// the x-axis.
|
||||
return simplify(subtractExpr(expression.lhs, expression.rhs));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sampling
|
||||
|
||||
export function sample(
|
||||
expression: MathExpression,
|
||||
variable: string,
|
||||
xMin: number,
|
||||
xMax: number,
|
||||
count: number,
|
||||
usesDegrees: boolean,
|
||||
): GraphSegment[] {
|
||||
if (count <= 1 || xMax <= xMin) return [];
|
||||
const segments: GraphSegment[] = [];
|
||||
let current: GraphPoint[] = [];
|
||||
const step = (xMax - xMin) / (count - 1);
|
||||
let previousY: number | null = null;
|
||||
|
||||
for (let index = 0; index < count; index++) {
|
||||
const x = xMin + index * step;
|
||||
const y = evaluateValue(expression, { [variable]: x }, usesDegrees);
|
||||
if (y === null || !Number.isFinite(y) || Math.abs(y) >= POLE_THRESHOLD) {
|
||||
// Undefined or blown up: close the run.
|
||||
if (current.length > 1) segments.push({ points: current });
|
||||
current = [];
|
||||
previousY = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
// A jump this large between adjacent samples is a pole, not a slope.
|
||||
// tan(x) is the canonical case: without this the curve gets a vertical
|
||||
// line at every asymptote.
|
||||
if (previousY !== null && Math.abs(y - previousY) > (xMax - xMin) * 50) {
|
||||
if (current.length > 1) segments.push({ points: current });
|
||||
current = [];
|
||||
}
|
||||
current.push({ x, y });
|
||||
previousY = y;
|
||||
}
|
||||
if (current.length > 1) segments.push({ points: current });
|
||||
return segments;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Autoscale
|
||||
|
||||
/**
|
||||
* Percentile-based rather than min/max: one spike near a pole would
|
||||
* otherwise compress the interesting part of the curve into a flat line.
|
||||
*/
|
||||
export function autoscale(xWindow: GraphViewport, yValues: number[]): GraphViewport {
|
||||
const finite = yValues.filter((y) => Number.isFinite(y) && Math.abs(y) < POLE_THRESHOLD).sort((a, b) => a - b);
|
||||
if (finite.length <= 2) {
|
||||
return { xMin: xWindow.xMin, xMax: xWindow.xMax, yMin: -10, yMax: 10 };
|
||||
}
|
||||
const lowIndex = Math.floor(finite.length * 0.02);
|
||||
const highIndex = Math.floor(finite.length * 0.98);
|
||||
let low = finite[Math.min(lowIndex, finite.length - 1)]!;
|
||||
let high = finite[Math.min(highIndex, finite.length - 1)]!;
|
||||
|
||||
// Always show the x-axis when the curve comes near it — a graph that omits
|
||||
// y = 0 reads as if the function never crosses.
|
||||
if (low > 0 && low < high * 0.5) low = 0;
|
||||
if (high < 0 && high > low * 0.5) high = 0;
|
||||
|
||||
if (high - low < 1e-9) {
|
||||
const centre = (high + low) / 2;
|
||||
low = centre - 1;
|
||||
high = centre + 1;
|
||||
}
|
||||
const padding = (high - low) * 0.1;
|
||||
return {
|
||||
xMin: xWindow.xMin,
|
||||
xMax: xWindow.xMax,
|
||||
yMin: low - padding,
|
||||
yMax: high + padding,
|
||||
};
|
||||
}
|
||||
|
||||
export function clip(segments: GraphSegment[], viewport: GraphViewport): GraphSegment[] {
|
||||
const result: GraphSegment[] = [];
|
||||
for (const segment of segments) {
|
||||
let current: GraphPoint[] = [];
|
||||
for (const point of segment.points) {
|
||||
if (viewportContainsY(viewport, point.y)) {
|
||||
current.push(point);
|
||||
} else if (current.length > 0) {
|
||||
// Keep one out-of-range point so the line exits the frame rather than
|
||||
// stopping short of the edge.
|
||||
current.push(point);
|
||||
result.push({ points: current });
|
||||
current = [];
|
||||
}
|
||||
}
|
||||
if (current.length > 1) result.push({ points: current });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Axes
|
||||
|
||||
/**
|
||||
* "Nice" tick spacing — 1, 2, 5, 10 × 10^n — so labels are round numbers a
|
||||
* person can read at a glance on the lens.
|
||||
*/
|
||||
export function axis(lower: number, upper: number, targetTicks = 10): GraphAxis {
|
||||
const span = upper - lower;
|
||||
if (span <= 0 || !Number.isFinite(span)) return { ticks: [], step: 1 };
|
||||
const rough = span / targetTicks;
|
||||
const magnitude = Math.pow(10, Math.floor(Math.log10(rough)));
|
||||
const normalized = rough / magnitude;
|
||||
let step: number;
|
||||
if (normalized <= 1) step = magnitude;
|
||||
else if (normalized <= 2) step = 2 * magnitude;
|
||||
else if (normalized <= 5) step = 5 * magnitude;
|
||||
else step = 10 * magnitude;
|
||||
|
||||
const ticks: number[] = [];
|
||||
let value = Math.ceil(lower / step) * step;
|
||||
while (value <= upper && ticks.length < 64) {
|
||||
// Snap a near-zero tick to exactly zero so the axis line and its label
|
||||
// agree.
|
||||
ticks.push(Math.abs(value) < step * 1e-9 ? 0 : value);
|
||||
value += step;
|
||||
}
|
||||
return { ticks, step };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Markers
|
||||
|
||||
export function markers(
|
||||
expression: MathExpression,
|
||||
variable: string,
|
||||
xMin: number,
|
||||
xMax: number,
|
||||
): GraphMarker[] {
|
||||
const result: GraphMarker[] = [];
|
||||
|
||||
const yIntercept = evaluateValue(expression, { [variable]: 0 });
|
||||
if (yIntercept !== null && Number.isFinite(yIntercept) && xMin <= 0 && xMax >= 0) {
|
||||
result.push({
|
||||
kind: "yIntercept",
|
||||
point: { x: 0, y: yIntercept },
|
||||
label: `(0, ${describeNumber(fromDecimal(yIntercept))})`,
|
||||
});
|
||||
}
|
||||
|
||||
// Roots: exact when the curve is a polynomial, sampled otherwise.
|
||||
const polynomial = Polynomial.extract(expression, variable);
|
||||
if (polynomial) {
|
||||
for (const root of numericRoots(polynomial, [xMin, xMax], 4_000)) {
|
||||
result.push({
|
||||
kind: "root",
|
||||
point: { x: root, y: 0 },
|
||||
label: `(${describeNumber(fromDecimal(root))}, 0)`,
|
||||
});
|
||||
}
|
||||
}
|
||||
return result.slice(0, 12);
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
// Dense coefficient vector in one variable, `coefficients[i]` multiplying
|
||||
// `x^i`. Extracting one of these is how the solver decides what technique
|
||||
// applies — degree 1 is a rearrangement, degree 2 is the quadratic formula,
|
||||
// higher degrees go to rational-root plus a numeric fallback.
|
||||
|
||||
import {
|
||||
type MathExpression,
|
||||
addExpr,
|
||||
constantValue,
|
||||
int,
|
||||
multiplyExpr,
|
||||
negate,
|
||||
num,
|
||||
powerExpr,
|
||||
variable as variableExpr,
|
||||
} from "./expression";
|
||||
import {
|
||||
type MathNumber,
|
||||
add,
|
||||
doubleValue,
|
||||
greatestCommonDivisor,
|
||||
integer,
|
||||
integerValue,
|
||||
isOne,
|
||||
isZero,
|
||||
multiply,
|
||||
negated,
|
||||
numberEquals,
|
||||
real,
|
||||
} from "./math-number";
|
||||
|
||||
export class Polynomial {
|
||||
readonly coefficients: MathNumber[];
|
||||
readonly variable: string;
|
||||
|
||||
constructor(coefficients: MathNumber[], variable: string) {
|
||||
this.coefficients = [...coefficients];
|
||||
this.variable = variable;
|
||||
while (this.coefficients.length > 1 && isZero(this.coefficients[this.coefficients.length - 1]!)) {
|
||||
this.coefficients.pop();
|
||||
}
|
||||
if (this.coefficients.length === 0) this.coefficients.push(integer(0));
|
||||
}
|
||||
|
||||
get degree(): number {
|
||||
return this.coefficients.length - 1;
|
||||
}
|
||||
|
||||
get isZero(): boolean {
|
||||
return this.coefficients.every(isZero);
|
||||
}
|
||||
|
||||
at(power: number): MathNumber {
|
||||
return power < this.coefficients.length ? this.coefficients[power]! : integer(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build from an expression, or null when it is not a polynomial in
|
||||
* `variable` (a variable inside `sin`, a symbolic exponent, `1/x`).
|
||||
*/
|
||||
static extract(expression: MathExpression, variable: string): Polynomial | null {
|
||||
const coefficients: MathNumber[] = [];
|
||||
if (!accumulate(expression, variable, integer(1), coefficients)) return null;
|
||||
return new Polynomial(coefficients, variable);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Evaluation
|
||||
|
||||
/**
|
||||
* Horner's method — fewer operations and less rounding drift than summing
|
||||
* `a_i * x^i` term by term, which matters for the numeric root refinement.
|
||||
*/
|
||||
value(x: number): number {
|
||||
let result = 0;
|
||||
for (let index = this.coefficients.length - 1; index >= 0; index--) {
|
||||
result = result * x + doubleValue(this.coefficients[index]!);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
get derivative(): Polynomial {
|
||||
if (this.degree <= 0) return new Polynomial([integer(0)], this.variable);
|
||||
const derived: MathNumber[] = [];
|
||||
for (let power = 1; power <= this.degree; power++) {
|
||||
derived.push(multiply(this.at(power), integer(power)));
|
||||
}
|
||||
return new Polynomial(derived, this.variable);
|
||||
}
|
||||
|
||||
expression(): MathExpression {
|
||||
const terms: MathExpression[] = [];
|
||||
for (let power = this.degree; power >= 0; power--) {
|
||||
const coefficient = this.at(power);
|
||||
if (isZero(coefficient)) continue;
|
||||
let variablePart: MathExpression | null;
|
||||
if (power === 0) {
|
||||
variablePart = null;
|
||||
} else if (power === 1) {
|
||||
variablePart = variableExpr(this.variable);
|
||||
} else {
|
||||
variablePart = powerExpr(variableExpr(this.variable), int(power));
|
||||
}
|
||||
if (!variablePart) {
|
||||
terms.push(num(coefficient));
|
||||
continue;
|
||||
}
|
||||
if (isOne(coefficient)) {
|
||||
terms.push(variablePart);
|
||||
} else if (numberEquals(coefficient, integer(-1))) {
|
||||
terms.push(negate(variablePart));
|
||||
} else {
|
||||
terms.push(multiplyExpr([num(coefficient), variablePart]));
|
||||
}
|
||||
}
|
||||
if (terms.length === 0) return int(0);
|
||||
return terms.length === 1 ? terms[0]! : addExpr(terms);
|
||||
}
|
||||
|
||||
/**
|
||||
* Divide out a known root, returning the depressed polynomial. Used after a
|
||||
* rational root is found so the remainder can be solved in closed form.
|
||||
*/
|
||||
dividingByRoot(root: MathNumber): Polynomial {
|
||||
if (this.degree < 1) return this;
|
||||
const quotient: MathNumber[] = new Array(this.degree).fill(integer(0));
|
||||
let carry: MathNumber = integer(0);
|
||||
for (let power = this.degree; power >= 1; power--) {
|
||||
const coefficient = add(this.at(power), carry);
|
||||
quotient[power - 1] = coefficient;
|
||||
carry = multiply(coefficient, root);
|
||||
}
|
||||
return new Polynomial(quotient, this.variable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Integer coefficients after clearing denominators, for the rational root
|
||||
* theorem. Only meaningful when every coefficient is exact.
|
||||
*/
|
||||
get integerCoefficients(): number[] | null {
|
||||
let multiplier = 1;
|
||||
for (const coefficient of this.coefficients) {
|
||||
if (coefficient.kind === "integer") continue;
|
||||
if (coefficient.kind === "real") return null;
|
||||
multiplier = (multiplier / greatestCommonDivisor(multiplier, coefficient.d)) * coefficient.d;
|
||||
if (multiplier >= 1_000_000) return null;
|
||||
}
|
||||
const scaled: number[] = [];
|
||||
for (const coefficient of this.coefficients) {
|
||||
const value = integerValue(multiply(coefficient, integer(multiplier)));
|
||||
if (value === null) return null;
|
||||
scaled.push(value);
|
||||
}
|
||||
return scaled;
|
||||
}
|
||||
}
|
||||
|
||||
function accumulate(
|
||||
expression: MathExpression,
|
||||
variable: string,
|
||||
scale: MathNumber,
|
||||
coefficients: MathNumber[],
|
||||
): boolean {
|
||||
switch (expression.type) {
|
||||
case "number":
|
||||
addAt(multiply(scale, expression.value), 0, coefficients);
|
||||
return true;
|
||||
|
||||
case "constant":
|
||||
addAt(multiply(scale, real(constantValue(expression.constant))), 0, coefficients);
|
||||
return true;
|
||||
|
||||
case "variable":
|
||||
if (expression.name === variable) {
|
||||
addAt(scale, 1, coefficients);
|
||||
return true;
|
||||
}
|
||||
// Another free variable makes this not a single-variable polynomial —
|
||||
// refuse rather than silently treating it as a constant, which would
|
||||
// produce a confidently wrong root.
|
||||
return false;
|
||||
|
||||
case "negate":
|
||||
return accumulate(expression.inner, variable, negated(scale), coefficients);
|
||||
|
||||
case "add":
|
||||
for (const term of expression.terms) {
|
||||
if (!accumulate(term, variable, scale, coefficients)) return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
case "multiply": {
|
||||
// Multiply out: each factor must itself be a polynomial, and the
|
||||
// product of their coefficient vectors is the result.
|
||||
let product: MathNumber[] = [integer(1)];
|
||||
for (const factor of expression.factors) {
|
||||
const factorCoefficients: MathNumber[] = [];
|
||||
if (!accumulate(factor, variable, integer(1), factorCoefficients)) return false;
|
||||
product = convolve(product, factorCoefficients);
|
||||
if (product.length > 64) return false;
|
||||
}
|
||||
for (let power = 0; power < product.length; power++) {
|
||||
addAt(multiply(scale, product[power]!), power, coefficients);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
case "power": {
|
||||
const exponentNumber = expression.exponent.type === "number" ? expression.exponent.value : null;
|
||||
const power = exponentNumber ? integerValue(exponentNumber) : null;
|
||||
if (power === null || power < 0 || power > 32) return false;
|
||||
const baseCoefficients: MathNumber[] = [];
|
||||
if (!accumulate(expression.base, variable, integer(1), baseCoefficients)) return false;
|
||||
let product: MathNumber[] = [integer(1)];
|
||||
for (let step = 0; step < power; step++) {
|
||||
product = convolve(product, baseCoefficients);
|
||||
if (product.length > 64) return false;
|
||||
}
|
||||
for (let index = 0; index < product.length; index++) {
|
||||
addAt(multiply(scale, product[index]!), index, coefficients);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
case "function":
|
||||
case "relation":
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function addAt(value: MathNumber, power: number, coefficients: MathNumber[]): void {
|
||||
while (coefficients.length <= power) coefficients.push(integer(0));
|
||||
coefficients[power] = add(coefficients[power]!, value);
|
||||
}
|
||||
|
||||
function convolve(lhs: MathNumber[], rhs: MathNumber[]): MathNumber[] {
|
||||
if (lhs.length === 0 || rhs.length === 0) return [integer(0)];
|
||||
const result: MathNumber[] = new Array(lhs.length + rhs.length - 1).fill(integer(0));
|
||||
for (let i = 0; i < lhs.length; i++) {
|
||||
if (isZero(lhs[i]!)) continue;
|
||||
for (let j = 0; j < rhs.length; j++) {
|
||||
if (isZero(rhs[j]!)) continue;
|
||||
result[i + j] = add(result[i + j]!, multiply(lhs[i]!, rhs[j]!));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
// The command parser and the stateful session. Stateful on purpose: "graph
|
||||
// it" is only meaningful with respect to the problem already on screen, and
|
||||
// requiring the wearer to restate the equation to see its graph would defeat
|
||||
// the point.
|
||||
|
||||
import {
|
||||
type MathExpression,
|
||||
variablesOf,
|
||||
} from "./expression";
|
||||
import { describeNumber, fromDecimal } from "./math-number";
|
||||
import { type AdvancedTopic, answerAdvanced, parseAdvanced } from "./advanced";
|
||||
import { type EvaluatorContext, radiansContext } from "./evaluator";
|
||||
import { parseSpoken } from "./parser";
|
||||
import { MathParseError } from "./lexer";
|
||||
import {
|
||||
type MathSolution,
|
||||
type SolutionStep,
|
||||
solutionHeadline,
|
||||
solve as solveExpression,
|
||||
} from "./solver";
|
||||
import { type Graph, type GraphViewport, functionBody, plot } from "./plotter";
|
||||
import { differentiate, integrateNumeric } from "./derivative";
|
||||
import { plain } from "./text-renderer";
|
||||
import { type MathWorkload } from "./workload";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Commands
|
||||
|
||||
/**
|
||||
* What the wearer asked for. Parsed from speech so "graph it" and "explain
|
||||
* it" work as follow-ups to a problem already on the glasses, without
|
||||
* restating it.
|
||||
*/
|
||||
export type MathCommand =
|
||||
/** A new problem to solve or evaluate. */
|
||||
| { kind: "problem"; text: string }
|
||||
| { kind: "graph" }
|
||||
| { kind: "explain" }
|
||||
| { kind: "nextStep" }
|
||||
| { kind: "previousStep" }
|
||||
| { kind: "derivative"; variable: string | null }
|
||||
| { kind: "integrate"; variable: string | null; from: number; to: number }
|
||||
| { kind: "restate" }
|
||||
| { kind: "clear" }
|
||||
/**
|
||||
* A named advanced topic — primality, an integral, a limit, a shape's
|
||||
* area. These carry their own arguments rather than acting on a standing
|
||||
* expression, which is why they are a separate case.
|
||||
*/
|
||||
| { kind: "advanced"; topic: AdvancedTopic };
|
||||
|
||||
/**
|
||||
* Recognise a follow-up. Returns null when the utterance is not a math
|
||||
* command at all, so the caller can leave unrelated speech alone.
|
||||
*/
|
||||
export function parseCommand(utterance: string): MathCommand | null {
|
||||
const text = utterance.toLowerCase().replace(/^[ .,!?]+|[ .,!?]+$/g, "");
|
||||
|
||||
// Follow-ups first: they are short and would otherwise be parsed as
|
||||
// (nonsense) expressions.
|
||||
//
|
||||
// The bare verb is listed alongside every "it"/"that"/"this" form on
|
||||
// purpose: these are the three commands a wearer is TOLD they can say, and
|
||||
// someone who has been shown "Graph" will say "graph" as often as
|
||||
// "graph it". Leaving the bare form out makes the feature look broken in
|
||||
// exactly the case the user was taught.
|
||||
switch (text) {
|
||||
case "graph":
|
||||
case "graph it":
|
||||
case "graph that":
|
||||
case "graph this":
|
||||
case "plot":
|
||||
case "plot it":
|
||||
case "plot that":
|
||||
case "plot this":
|
||||
case "show the graph":
|
||||
case "draw it":
|
||||
case "show me the graph":
|
||||
return { kind: "graph" };
|
||||
case "explain":
|
||||
case "explain it":
|
||||
case "explain that":
|
||||
case "explain this":
|
||||
case "show the steps":
|
||||
case "show your work":
|
||||
case "how did you get that":
|
||||
case "walk me through it":
|
||||
case "step by step":
|
||||
return { kind: "explain" };
|
||||
// "Solve it" on a problem already on the lens is a request for the answer
|
||||
// again, not a re-parse — `restate` is exactly that, and routing it here
|
||||
// means the standing problem is never silently re-solved with a fresh
|
||||
// (and possibly worse) reading of the same words.
|
||||
case "solve":
|
||||
case "solve it":
|
||||
case "solve that":
|
||||
case "solve this":
|
||||
case "work it out":
|
||||
case "what is the answer":
|
||||
case "what's the answer":
|
||||
case "whats the answer":
|
||||
case "answer it":
|
||||
return { kind: "restate" };
|
||||
case "next":
|
||||
case "next step":
|
||||
case "continue":
|
||||
case "go on":
|
||||
case "and then":
|
||||
return { kind: "nextStep" };
|
||||
case "back":
|
||||
case "previous":
|
||||
case "previous step":
|
||||
case "go back":
|
||||
case "last step":
|
||||
return { kind: "previousStep" };
|
||||
case "say it again":
|
||||
case "repeat that":
|
||||
case "what was it":
|
||||
case "restate":
|
||||
case "again":
|
||||
return { kind: "restate" };
|
||||
case "clear":
|
||||
case "reset":
|
||||
case "start over":
|
||||
case "never mind":
|
||||
case "forget it":
|
||||
return { kind: "clear" };
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
const derivative = matchDerivative(text);
|
||||
if (derivative !== null) return { kind: "derivative", variable: derivative };
|
||||
// Advanced topics BEFORE the plain-integral shortcut and the
|
||||
// looks-like-maths gate: "the integral of x squared from 0 to 3" and "is 91
|
||||
// prime" both contain digits and operator words, and the expression parser
|
||||
// would make nonsense of either.
|
||||
const topic = parseAdvanced(utterance);
|
||||
if (topic) return { kind: "advanced", topic };
|
||||
const integral = matchIntegral(text);
|
||||
if (integral) return integral;
|
||||
|
||||
// Anything with a digit, an operator word, or a relation is a problem.
|
||||
if (!looksLikeMath(text)) return null;
|
||||
return { kind: "problem", text: utterance };
|
||||
}
|
||||
|
||||
/** Distinguishes "no derivative request" (null) from "derivative of the default variable". */
|
||||
function matchDerivative(text: string): string | null {
|
||||
const triggers = [
|
||||
"differentiate",
|
||||
"take the derivative",
|
||||
"the derivative",
|
||||
"derivative of",
|
||||
"d by d",
|
||||
"find the derivative",
|
||||
];
|
||||
if (!triggers.some((trigger) => text.includes(trigger))) return null;
|
||||
// "derivative with respect to t"
|
||||
const marker = "with respect to ";
|
||||
const index = text.indexOf(marker);
|
||||
if (index >= 0) {
|
||||
const tail = text.slice(index + marker.length).trim();
|
||||
const first = tail.split(/\s+/)[0];
|
||||
if (first && first.length <= 12) return first;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function matchIntegral(text: string): MathCommand | null {
|
||||
if (!text.includes("integral") && !text.includes("integrate")) return null;
|
||||
// "integrate from 0 to 5"
|
||||
const match = text.match(/from\s+(-?[0-9.]+)\s+to\s+(-?[0-9.]+)/);
|
||||
if (!match) return null;
|
||||
const lower = Number(match[1]);
|
||||
const upper = Number(match[2]);
|
||||
if (!Number.isFinite(lower) || !Number.isFinite(upper)) return null;
|
||||
return { kind: "integrate", variable: null, from: lower, to: upper };
|
||||
}
|
||||
|
||||
/**
|
||||
* A cheap gate so ordinary conversation is not parsed as arithmetic. The
|
||||
* continuous-listening path hands this every utterance in the room; without
|
||||
* the gate, "I'll see you at four" becomes a math problem.
|
||||
*/
|
||||
export function looksLikeMath(text: string): boolean {
|
||||
const operatorWords = [
|
||||
"plus",
|
||||
"minus",
|
||||
"times",
|
||||
"divided",
|
||||
"equals",
|
||||
"squared",
|
||||
"cubed",
|
||||
"square root",
|
||||
"solve",
|
||||
"what is",
|
||||
"calculate",
|
||||
"percent",
|
||||
"factorial",
|
||||
"to the power",
|
||||
"log",
|
||||
"sine",
|
||||
"cosine",
|
||||
"tangent",
|
||||
];
|
||||
const hasOperatorWord = operatorWords.some((word) => text.includes(word));
|
||||
const hasSymbol = /[+\-*/^=<>]/.test(text);
|
||||
const hasDigit = /\d/.test(text);
|
||||
// Spelled-out numbers count too. "what is two plus two" has an operator
|
||||
// word and no digit at all, and requiring a digit made the single most
|
||||
// obvious test phrase fall straight through the gate.
|
||||
const numberWords = [
|
||||
"zero",
|
||||
"one",
|
||||
"two",
|
||||
"three",
|
||||
"four",
|
||||
"five",
|
||||
"six",
|
||||
"seven",
|
||||
"eight",
|
||||
"nine",
|
||||
"ten",
|
||||
"eleven",
|
||||
"twelve",
|
||||
"twenty",
|
||||
"thirty",
|
||||
"forty",
|
||||
"fifty",
|
||||
"hundred",
|
||||
"thousand",
|
||||
"million",
|
||||
];
|
||||
const hasNumberWord = numberWords.some((word) => new RegExp(`\\b${word}\\b`).test(text));
|
||||
// A bare number is not a problem; a number with an operation is.
|
||||
return (hasDigit || hasSymbol || hasNumberWord) && (hasOperatorWord || hasSymbol);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Result
|
||||
|
||||
export type MathSessionPayload =
|
||||
| { kind: "solution"; solution: MathSolution }
|
||||
| { kind: "graph"; graph: Graph }
|
||||
| { kind: "step"; step: SolutionStep; index: number; total: number }
|
||||
| { kind: "message"; message: string }
|
||||
| { kind: "failure"; message: string }
|
||||
/**
|
||||
* An advanced-topic answer, which has its own field list rather than a
|
||||
* solution's step sequence.
|
||||
*/
|
||||
| { kind: "topic"; headline: string; detail: string; fields: string[] };
|
||||
|
||||
export type MathSessionResult = {
|
||||
payload: MathSessionPayload;
|
||||
/** One short line for the glasses. */
|
||||
headline: string;
|
||||
/** Fuller text for the answer view and for spoken readback. */
|
||||
detail: string;
|
||||
/**
|
||||
* Work this answer could not finish at the fast depth. The caller decides
|
||||
* whether to offer the wearer a longer run, or let the shallow answer
|
||||
* stand.
|
||||
*/
|
||||
unresolvedWorkload: MathWorkload | null;
|
||||
};
|
||||
|
||||
function result(
|
||||
payload: MathSessionPayload,
|
||||
headline: string,
|
||||
detail: string,
|
||||
unresolvedWorkload: MathWorkload | null = null,
|
||||
): MathSessionResult {
|
||||
return { payload, headline, detail, unresolvedWorkload };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Session
|
||||
|
||||
/** Holds one problem and everything derived from it, so follow-ups work. */
|
||||
export class MathSession {
|
||||
private expression: MathExpression | null = null;
|
||||
private solution: MathSolution | null = null;
|
||||
private stepIndex = 0;
|
||||
private usesDegrees: boolean;
|
||||
|
||||
constructor(usesDegrees = false) {
|
||||
this.usesDegrees = usesDegrees;
|
||||
}
|
||||
|
||||
get hasProblem(): boolean {
|
||||
return this.expression !== null;
|
||||
}
|
||||
|
||||
get currentSolution(): MathSolution | null {
|
||||
return this.solution;
|
||||
}
|
||||
|
||||
setUsesDegrees(value: boolean): void {
|
||||
this.usesDegrees = value;
|
||||
}
|
||||
|
||||
private get context(): EvaluatorContext {
|
||||
const context = radiansContext();
|
||||
context.usesDegrees = this.usesDegrees;
|
||||
return context;
|
||||
}
|
||||
|
||||
// Entry point --------------------------------------------------------------
|
||||
|
||||
handle(utterance: string): MathSessionResult | null {
|
||||
const command = parseCommand(utterance);
|
||||
if (!command) return null;
|
||||
return this.execute(command);
|
||||
}
|
||||
|
||||
execute(command: MathCommand): MathSessionResult {
|
||||
switch (command.kind) {
|
||||
case "problem":
|
||||
return this.solve(command.text);
|
||||
case "graph":
|
||||
return this.graph();
|
||||
case "explain":
|
||||
return this.explain();
|
||||
case "nextStep":
|
||||
return this.moveStep(1);
|
||||
case "previousStep":
|
||||
return this.moveStep(-1);
|
||||
case "derivative":
|
||||
return this.differentiate(command.variable === "" ? null : command.variable);
|
||||
case "integrate":
|
||||
return this.integrate(command.variable, command.from, command.to);
|
||||
case "restate":
|
||||
return this.restate();
|
||||
case "advanced": {
|
||||
const answer = answerAdvanced(command.topic);
|
||||
return result(
|
||||
{
|
||||
kind: "topic",
|
||||
headline: answer.headline,
|
||||
detail: answer.detail,
|
||||
fields: answer.fields.map(([label, value]) => `${label}: ${value}`),
|
||||
},
|
||||
answer.headline,
|
||||
answer.detail,
|
||||
answer.unresolvedWorkload,
|
||||
);
|
||||
}
|
||||
case "clear":
|
||||
this.expression = null;
|
||||
this.solution = null;
|
||||
this.stepIndex = 0;
|
||||
return result({ kind: "message", message: "Cleared" }, "Cleared", "Ready for a new problem.");
|
||||
}
|
||||
}
|
||||
|
||||
// Commands -----------------------------------------------------------------
|
||||
|
||||
solve(text: string): MathSessionResult {
|
||||
let parsed: MathExpression;
|
||||
try {
|
||||
parsed = parseSpoken(text);
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof MathParseError ? error.message : String((error as Error)?.message ?? error);
|
||||
return result({ kind: "failure", message }, "Could not read that", message);
|
||||
}
|
||||
const solved = solveExpression(parsed, null, this.context);
|
||||
this.expression = parsed;
|
||||
this.solution = solved;
|
||||
this.stepIndex = 0;
|
||||
return result(
|
||||
{ kind: "solution", solution: solved },
|
||||
solutionHeadline(solved),
|
||||
`${plain(solved.restatement)} → ${solutionHeadline(solved)}`,
|
||||
);
|
||||
}
|
||||
|
||||
graph(viewport: GraphViewport | null = null): MathSessionResult {
|
||||
if (!this.expression) return this.noProblem();
|
||||
const plotted = plot([this.expression], {
|
||||
viewport: viewport ?? undefined,
|
||||
usesDegrees: this.usesDegrees,
|
||||
});
|
||||
const pointCount = plotted.plots.reduce(
|
||||
(total, entry) => total + entry.segments.reduce((count, segment) => count + segment.points.length, 0),
|
||||
0,
|
||||
);
|
||||
if (pointCount <= 1) {
|
||||
return result(
|
||||
{ kind: "failure", message: "Nothing to plot" },
|
||||
"Nothing to plot",
|
||||
"That expression has no real values in the visible window.",
|
||||
);
|
||||
}
|
||||
const label = plotted.plots[0]?.label ?? "";
|
||||
return result(
|
||||
{ kind: "graph", graph: plotted },
|
||||
`y = ${label}`,
|
||||
`x from ${format(plotted.viewport.xMin)} to ${format(plotted.viewport.xMax)}, ` +
|
||||
`y from ${format(plotted.viewport.yMin)} to ${format(plotted.viewport.yMax)}`,
|
||||
);
|
||||
}
|
||||
|
||||
explain(): MathSessionResult {
|
||||
const solution = this.solution;
|
||||
if (!solution || solution.steps.length === 0) return this.noProblem();
|
||||
this.stepIndex = 0;
|
||||
return this.stepResult(0, solution);
|
||||
}
|
||||
|
||||
private moveStep(delta: number): MathSessionResult {
|
||||
const solution = this.solution;
|
||||
if (!solution || solution.steps.length === 0) return this.noProblem();
|
||||
// Clamp rather than wrap: a wearer scrolling past the end should land on
|
||||
// the answer and stay there, not loop back to the start.
|
||||
this.stepIndex = Math.max(0, Math.min(solution.steps.length - 1, this.stepIndex + delta));
|
||||
return this.stepResult(this.stepIndex, solution);
|
||||
}
|
||||
|
||||
private stepResult(index: number, solution: MathSolution): MathSessionResult {
|
||||
const step = solution.steps[index]!;
|
||||
return result(
|
||||
{ kind: "step", step, index, total: solution.steps.length },
|
||||
`${index + 1}/${solution.steps.length} ${step.title}`,
|
||||
`${plain(step.expression)}\n${step.detail}`,
|
||||
);
|
||||
}
|
||||
|
||||
differentiate(requestedVariable: string | null): MathSessionResult {
|
||||
if (!this.expression) return this.noProblem();
|
||||
const body = functionBody(this.expression);
|
||||
const variable = requestedVariable ?? variablesOf(body)[0] ?? "x";
|
||||
const derived = differentiate(body, variable);
|
||||
const derivedSolution: MathSolution = {
|
||||
kind: { kind: "simplified", value: derived },
|
||||
variable,
|
||||
steps: [
|
||||
{
|
||||
id: 0,
|
||||
title: "Original",
|
||||
expression: body,
|
||||
detail: `Differentiate with respect to ${variable}.`,
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
title: "Derivative",
|
||||
expression: derived,
|
||||
detail: "Apply the power, product, and chain rules, then simplify.",
|
||||
},
|
||||
],
|
||||
restatement: body,
|
||||
};
|
||||
this.expression = derived;
|
||||
this.solution = derivedSolution;
|
||||
this.stepIndex = 0;
|
||||
return result(
|
||||
{ kind: "solution", solution: derivedSolution },
|
||||
`d/d${variable} = ${plain(derived)}`,
|
||||
`The derivative of ${plain(body)} with respect to ${variable} is ${plain(derived)}.`,
|
||||
);
|
||||
}
|
||||
|
||||
integrate(requestedVariable: string | null, lower: number, upper: number): MathSessionResult {
|
||||
if (!this.expression) return this.noProblem();
|
||||
const body = functionBody(this.expression);
|
||||
const variable = requestedVariable ?? variablesOf(body)[0] ?? "x";
|
||||
const area = integrateNumeric(body, variable, lower, upper);
|
||||
if (area === null) {
|
||||
return result(
|
||||
{ kind: "failure", message: "Could not integrate over that range" },
|
||||
"Could not integrate",
|
||||
`The function is undefined somewhere between ${format(lower)} and ${format(upper)}.`,
|
||||
);
|
||||
}
|
||||
const value = fromDecimal(area);
|
||||
return result(
|
||||
{ kind: "message", message: describeNumber(value) },
|
||||
`∫ = ${describeNumber(value)}`,
|
||||
`The definite integral of ${plain(body)} d${variable} ` +
|
||||
`from ${format(lower)} to ${format(upper)} is ${describeNumber(value)}.`,
|
||||
);
|
||||
}
|
||||
|
||||
restate(): MathSessionResult {
|
||||
const solution = this.solution;
|
||||
if (!solution) return this.noProblem();
|
||||
return result(
|
||||
{ kind: "solution", solution },
|
||||
solutionHeadline(solution),
|
||||
`${plain(solution.restatement)} → ${solutionHeadline(solution)}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Helpers ------------------------------------------------------------------
|
||||
|
||||
private noProblem(): MathSessionResult {
|
||||
return result(
|
||||
{ kind: "failure", message: "No problem yet" },
|
||||
"No problem yet",
|
||||
"Say an equation first, then ask to graph or explain it.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function format(value: number): string {
|
||||
return describeNumber(fromDecimal(value));
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
// Canonicalises an expression tree. The goal is not a full CAS — it is a
|
||||
// *stable canonical form*, because three downstream features depend on one:
|
||||
//
|
||||
// * the solver compares subtrees for equality to collect like terms,
|
||||
// * the step explanations need `2x + 3x` to visibly become `5x`,
|
||||
// * the renderers should not print `1 * x + 0`.
|
||||
//
|
||||
// Rewriting runs to a fixed point with an iteration cap, so a rule pair that
|
||||
// oscillates degrades to "stopped early" rather than hanging the app.
|
||||
|
||||
import {
|
||||
type MathExpression,
|
||||
type MathFunction,
|
||||
ONE,
|
||||
ZERO,
|
||||
addExpr,
|
||||
expressionEquals,
|
||||
fn,
|
||||
functionIsDefined,
|
||||
evaluateFunction,
|
||||
isOneExpr,
|
||||
isZeroExpr,
|
||||
multiplyExpr,
|
||||
negate,
|
||||
num,
|
||||
numberValue,
|
||||
powerExpr,
|
||||
relation,
|
||||
variablesOf,
|
||||
} from "./expression";
|
||||
import {
|
||||
type MathNumber,
|
||||
add,
|
||||
doubleValue,
|
||||
fromDecimal,
|
||||
integer,
|
||||
integerValue,
|
||||
isExact,
|
||||
isOne,
|
||||
isZero,
|
||||
isNegative,
|
||||
multiply,
|
||||
negated,
|
||||
numberEquals,
|
||||
raisedTo,
|
||||
rational,
|
||||
} from "./math-number";
|
||||
|
||||
const MAXIMUM_PASSES = 24;
|
||||
|
||||
export function simplify(expression: MathExpression): MathExpression {
|
||||
let current = expression;
|
||||
for (let iteration = 0; iteration < MAXIMUM_PASSES; iteration++) {
|
||||
const next = pass(current);
|
||||
if (expressionEquals(next, current)) return next;
|
||||
current = next;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// One rewrite pass
|
||||
|
||||
function pass(expression: MathExpression): MathExpression {
|
||||
switch (expression.type) {
|
||||
case "number":
|
||||
case "variable":
|
||||
case "constant":
|
||||
return expression;
|
||||
|
||||
case "negate": {
|
||||
const simplified = pass(expression.inner);
|
||||
const value = numberValue(simplified);
|
||||
if (value) return num(negated(value));
|
||||
// Double negation.
|
||||
if (simplified.type === "negate") return simplified.inner;
|
||||
return negate(simplified);
|
||||
}
|
||||
|
||||
case "add":
|
||||
return simplifySum(expression.terms.map(pass));
|
||||
|
||||
case "multiply":
|
||||
return simplifyProduct(expression.factors.map(pass));
|
||||
|
||||
case "power":
|
||||
return simplifyPower(pass(expression.base), pass(expression.exponent));
|
||||
|
||||
case "function": {
|
||||
const simplified = expression.args.map(pass);
|
||||
// Fold a constant argument, but only when the result stays clean —
|
||||
// `sqrt(2)` must remain symbolic, not become 1.4142135623730951 in the
|
||||
// middle of an exact solution.
|
||||
const first = simplified[0];
|
||||
if (first) {
|
||||
const value = numberValue(first);
|
||||
if (value) {
|
||||
const folded = foldFunction(expression.fn, value);
|
||||
if (folded) return num(folded);
|
||||
}
|
||||
}
|
||||
return fn(expression.fn, simplified);
|
||||
}
|
||||
|
||||
case "relation":
|
||||
return relation(expression.relation, pass(expression.lhs), pass(expression.rhs));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sums
|
||||
|
||||
function simplifySum(rawTerms: MathExpression[]): MathExpression {
|
||||
const flattened: MathExpression[] = [];
|
||||
for (const term of rawTerms) {
|
||||
if (term.type === "add") {
|
||||
flattened.push(...term.terms);
|
||||
} else {
|
||||
flattened.push(term);
|
||||
}
|
||||
}
|
||||
|
||||
// Collect like terms by their non-numeric part: 2x + 3x → 5x.
|
||||
let constantTotal: MathNumber = integer(0);
|
||||
const collected: { key: MathExpression; coefficient: MathNumber }[] = [];
|
||||
|
||||
for (const term of flattened) {
|
||||
const value = numberValue(term);
|
||||
if (value) {
|
||||
constantTotal = add(constantTotal, value);
|
||||
continue;
|
||||
}
|
||||
const [coefficient, key] = splitCoefficient(term);
|
||||
const existing = collected.find((entry) => expressionEquals(entry.key, key));
|
||||
if (existing) {
|
||||
existing.coefficient = add(existing.coefficient, coefficient);
|
||||
} else {
|
||||
collected.push({ key, coefficient });
|
||||
}
|
||||
}
|
||||
|
||||
const terms: MathExpression[] = [];
|
||||
for (const entry of collected) {
|
||||
if (isZero(entry.coefficient)) continue;
|
||||
terms.push(rebuild(entry.coefficient, entry.key));
|
||||
}
|
||||
// Stable ordering: highest polynomial degree first, which is how a person
|
||||
// writes it and how the quadratic solver expects to read it.
|
||||
terms.sort((a, b) => degree(b) - degree(a));
|
||||
|
||||
if (!isZero(constantTotal)) terms.push(num(constantTotal));
|
||||
if (terms.length === 0) return ZERO;
|
||||
return terms.length === 1 ? terms[0]! : addExpr(terms);
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a term into its numeric coefficient and the rest, so like terms can
|
||||
* be matched: `3 * x * y` → (3, x*y), `-x` → (-1, x).
|
||||
*/
|
||||
export function splitCoefficient(term: MathExpression): [MathNumber, MathExpression] {
|
||||
switch (term.type) {
|
||||
case "negate": {
|
||||
const [coefficient, key] = splitCoefficient(term.inner);
|
||||
return [negated(coefficient), key];
|
||||
}
|
||||
case "multiply": {
|
||||
let coefficient: MathNumber = integer(1);
|
||||
const rest: MathExpression[] = [];
|
||||
for (const factor of term.factors) {
|
||||
const value = numberValue(factor);
|
||||
if (value) {
|
||||
coefficient = multiply(coefficient, value);
|
||||
} else {
|
||||
rest.push(factor);
|
||||
}
|
||||
}
|
||||
if (rest.length === 0) return [coefficient, ONE];
|
||||
return [coefficient, rest.length === 1 ? rest[0]! : multiplyExpr(rest)];
|
||||
}
|
||||
default:
|
||||
return [integer(1), term];
|
||||
}
|
||||
}
|
||||
|
||||
function rebuild(coefficient: MathNumber, key: MathExpression): MathExpression {
|
||||
if (isOneExpr(key)) return num(coefficient);
|
||||
if (isOne(coefficient)) return key;
|
||||
if (numberEquals(coefficient, integer(-1))) return negate(key);
|
||||
return multiplyExpr([num(coefficient), key]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Products
|
||||
|
||||
function simplifyProduct(rawFactors: MathExpression[]): MathExpression {
|
||||
const flattened: MathExpression[] = [];
|
||||
let sign = false;
|
||||
for (const factor of rawFactors) {
|
||||
if (factor.type === "multiply") {
|
||||
flattened.push(...factor.factors);
|
||||
} else if (factor.type === "negate") {
|
||||
// Pull negation out to the front rather than leaving it buried, so
|
||||
// `(-x) * (-y)` cancels to `x * y`.
|
||||
sign = !sign;
|
||||
flattened.push(factor.inner);
|
||||
} else {
|
||||
flattened.push(factor);
|
||||
}
|
||||
}
|
||||
|
||||
let coefficient: MathNumber = integer(1);
|
||||
// Collect powers with matching bases: x * x^2 → x^3.
|
||||
const bases: { base: MathExpression; exponents: MathExpression[] }[] = [];
|
||||
|
||||
for (const factor of flattened) {
|
||||
const value = numberValue(factor);
|
||||
if (value) {
|
||||
coefficient = multiply(coefficient, value);
|
||||
continue;
|
||||
}
|
||||
const [base, exponent] = splitPower(factor);
|
||||
const existing = bases.find((entry) => expressionEquals(entry.base, base));
|
||||
if (existing) {
|
||||
existing.exponents.push(exponent);
|
||||
} else {
|
||||
bases.push({ base, exponents: [exponent] });
|
||||
}
|
||||
}
|
||||
|
||||
if (isZero(coefficient)) return ZERO;
|
||||
|
||||
const factors: MathExpression[] = [];
|
||||
for (const entry of bases) {
|
||||
const exponent = entry.exponents.length === 1 ? entry.exponents[0]! : simplify(addExpr(entry.exponents));
|
||||
if (isZeroExpr(exponent)) continue; // x^0 = 1
|
||||
if (isOneExpr(exponent)) {
|
||||
factors.push(entry.base);
|
||||
continue;
|
||||
}
|
||||
factors.push(powerExpr(entry.base, exponent));
|
||||
}
|
||||
|
||||
if (sign) coefficient = negated(coefficient);
|
||||
if (factors.length === 0) return num(coefficient);
|
||||
if (!isOne(coefficient)) {
|
||||
if (numberEquals(coefficient, integer(-1))) {
|
||||
return negate(factors.length === 1 ? factors[0]! : multiplyExpr(factors));
|
||||
}
|
||||
factors.unshift(num(coefficient));
|
||||
}
|
||||
return factors.length === 1 ? factors[0]! : multiplyExpr(factors);
|
||||
}
|
||||
|
||||
export function splitPower(expression: MathExpression): [MathExpression, MathExpression] {
|
||||
if (expression.type === "power") return [expression.base, expression.exponent];
|
||||
return [expression, ONE];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Powers
|
||||
|
||||
function simplifyPower(base: MathExpression, exponent: MathExpression): MathExpression {
|
||||
if (isZeroExpr(exponent)) return ONE; // x^0 = 1
|
||||
if (isOneExpr(exponent)) return base; // x^1 = x
|
||||
if (isOneExpr(base)) return ONE; // 1^n = 1
|
||||
const exponentValue = numberValue(exponent);
|
||||
if (isZeroExpr(base) && exponentValue && !isNegative(exponentValue)) return ZERO;
|
||||
|
||||
// Fold a numeric power only when it stays exact. `2^0.5` must stay
|
||||
// symbolic so an exact answer does not silently become a float.
|
||||
const baseValue = numberValue(base);
|
||||
if (baseValue && exponentValue) {
|
||||
const result = raisedTo(baseValue, exponentValue);
|
||||
if (isExact(result) || !isExact(baseValue) || !isExact(exponentValue)) {
|
||||
return num(result);
|
||||
}
|
||||
}
|
||||
// (x^a)^b = x^(a*b)
|
||||
if (base.type === "power") {
|
||||
return powerExpr(base.base, simplify(multiplyExpr([base.exponent, exponent])));
|
||||
}
|
||||
return powerExpr(base, exponent);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Function folding
|
||||
|
||||
/**
|
||||
* Fold only where the result is exact or the input was already inexact. This
|
||||
* is what keeps `sqrt(2)` symbolic while `sqrt(9)` becomes 3.
|
||||
*/
|
||||
function foldFunction(name: MathFunction, value: MathNumber): MathNumber | null {
|
||||
if (!functionIsDefined(name, doubleValue(value))) return null;
|
||||
|
||||
const asInt = integerValue(value);
|
||||
if (name === "factorial" && asInt !== null && asInt >= 0 && asInt <= 20) {
|
||||
let total = 1;
|
||||
for (let step = 2; step <= asInt; step++) total *= step;
|
||||
return integer(total);
|
||||
}
|
||||
if (name === "sqrt" && isExact(value)) {
|
||||
const exact = raisedTo(value, rational(1, 2));
|
||||
return isExact(exact) ? exact : null;
|
||||
}
|
||||
if (name === "floor" || name === "ceil" || name === "round" || name === "abs") {
|
||||
const result = evaluateFunction(name, doubleValue(value));
|
||||
return Number.isFinite(result) ? fromDecimal(result) : null;
|
||||
}
|
||||
// Inexact input already lost exactness, so folding costs nothing.
|
||||
if (isExact(value)) return null;
|
||||
const result = evaluateFunction(name, doubleValue(value));
|
||||
return Number.isFinite(result) ? { kind: "real", value: result } : null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Degree
|
||||
|
||||
const NON_POLYNOMIAL = Math.floor(Number.MAX_SAFE_INTEGER / 4);
|
||||
|
||||
/**
|
||||
* Polynomial degree in the given variable (or the highest across all
|
||||
* variables when none is named). Drives term ordering and lets the solver
|
||||
* pick a strategy.
|
||||
*/
|
||||
export function degree(expression: MathExpression, inVariable: string | null = null): number {
|
||||
switch (expression.type) {
|
||||
case "number":
|
||||
case "constant":
|
||||
return 0;
|
||||
case "variable":
|
||||
return inVariable === null || inVariable === expression.name ? 1 : 0;
|
||||
case "negate":
|
||||
return degree(expression.inner, inVariable);
|
||||
case "add":
|
||||
return expression.terms.reduce((highest, term) => Math.max(highest, degree(term, inVariable)), 0);
|
||||
case "multiply":
|
||||
return expression.factors.reduce((total, factor) => total + degree(factor, inVariable), 0);
|
||||
case "power": {
|
||||
const value = numberValue(expression.exponent);
|
||||
const power = value ? integerValue(value) : null;
|
||||
if (power === null) {
|
||||
// A symbolic exponent is not a polynomial degree; report 0 for a
|
||||
// constant base and a large sentinel otherwise so the solver does not
|
||||
// mistake it for something it can factor.
|
||||
return variablesOf(expression.base).length === 0 ? 0 : NON_POLYNOMIAL;
|
||||
}
|
||||
return degree(expression.base, inVariable) * power;
|
||||
}
|
||||
case "function":
|
||||
// Any variable inside a transcendental function makes this
|
||||
// non-polynomial.
|
||||
return expression.args.some((argument) => variablesOf(argument).length > 0) ? NON_POLYNOMIAL : 0;
|
||||
case "relation":
|
||||
return Math.max(degree(expression.lhs, inVariable), degree(expression.rhs, inVariable));
|
||||
}
|
||||
}
|
||||
|
||||
/** True when the expression is a genuine polynomial in `variable`. */
|
||||
export function isPolynomial(expression: MathExpression, inVariable: string): boolean {
|
||||
return degree(expression, inVariable) < NON_POLYNOMIAL / 2;
|
||||
}
|
||||
@@ -0,0 +1,781 @@
|
||||
// Solves what a person actually asks a calculator, in the order of
|
||||
// likelihood: evaluate an arithmetic expression, solve a linear or quadratic
|
||||
// equation, find polynomial roots, or fall back to a numeric search.
|
||||
//
|
||||
// Every branch records SolutionSteps as it goes, because "explain it" is a
|
||||
// first-class feature here rather than a reconstruction after the fact — a
|
||||
// post-hoc explanation of a numeric root search would be fiction.
|
||||
|
||||
import {
|
||||
type MathExpression,
|
||||
type MathRelation,
|
||||
ZERO,
|
||||
addExpr,
|
||||
divideExpr,
|
||||
expressionEquals,
|
||||
flippedRelation,
|
||||
fn,
|
||||
int,
|
||||
multiplyExpr,
|
||||
negate,
|
||||
num,
|
||||
numberValue,
|
||||
relation as relationExpr,
|
||||
spokenRelation,
|
||||
subtractExpr,
|
||||
variable as variableExpr,
|
||||
variablesOf,
|
||||
} from "./expression";
|
||||
import {
|
||||
type MathNumber,
|
||||
add,
|
||||
describeNumber,
|
||||
doubleValue,
|
||||
fromDecimal,
|
||||
integer,
|
||||
isExact,
|
||||
isNegative,
|
||||
isZero,
|
||||
multiply,
|
||||
negated,
|
||||
divide as divideNumber,
|
||||
raisedTo,
|
||||
rational,
|
||||
real,
|
||||
subtract,
|
||||
} from "./math-number";
|
||||
import { type EvaluatorContext, evaluateExact, evaluateValue, radiansContext } from "./evaluator";
|
||||
import { simplify } from "./simplifier";
|
||||
import { Polynomial } from "./polynomial";
|
||||
import { plain, renderNumber } from "./text-renderer";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Steps
|
||||
|
||||
/**
|
||||
* One line of "explain it". Recorded by the solver as it works rather than
|
||||
* reconstructed afterwards.
|
||||
*/
|
||||
export type SolutionStep = {
|
||||
id: number;
|
||||
/** Short imperative title — what was done ("Divide by 2"). */
|
||||
title: string;
|
||||
/** The expression AFTER this step. */
|
||||
expression: MathExpression;
|
||||
/** Plain-language reason, shown under the title. */
|
||||
detail: string;
|
||||
};
|
||||
|
||||
export function stepPlain(step: SolutionStep): string {
|
||||
return plain(step.expression);
|
||||
}
|
||||
|
||||
export class SolutionStepRecorder {
|
||||
readonly steps: SolutionStep[] = [];
|
||||
|
||||
add(title: string, expression: MathExpression, detail: string): void {
|
||||
// Collapse a step that changed nothing — "Simplify: 2x + 1" following
|
||||
// "Start: 2x + 1" is noise that makes a short solve look laborious.
|
||||
const last = this.steps[this.steps.length - 1];
|
||||
if (last && expressionEquals(last.expression, expression)) return;
|
||||
this.steps.push({ id: this.steps.length, title, expression, detail });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Solution
|
||||
|
||||
export type MathSolutionKind =
|
||||
/** A finite set of values for the unknown. */
|
||||
| { kind: "roots"; roots: MathExpression[] }
|
||||
/** The relation holds for every value (`x = x`). */
|
||||
| { kind: "identity" }
|
||||
/** It holds for none (`0 = 1`). */
|
||||
| { kind: "contradiction" }
|
||||
/** A single evaluated value — the answer to "what is 2+2". */
|
||||
| { kind: "value"; value: MathExpression }
|
||||
/** Simplified but not solved (no unknown to solve for). */
|
||||
| { kind: "simplified"; value: MathExpression }
|
||||
/** An inequality's solution interval. */
|
||||
| {
|
||||
kind: "interval";
|
||||
lower: MathExpression | null;
|
||||
upper: MathExpression | null;
|
||||
relation: MathRelation;
|
||||
};
|
||||
|
||||
export type MathSolution = {
|
||||
kind: MathSolutionKind;
|
||||
variable: string | null;
|
||||
steps: SolutionStep[];
|
||||
/**
|
||||
* The input as the engine understood it, so a wearer can confirm the
|
||||
* machine heard the same problem they said.
|
||||
*/
|
||||
restatement: MathExpression;
|
||||
};
|
||||
|
||||
/** The short line the glasses show. */
|
||||
export function solutionHeadline(solution: MathSolution): string {
|
||||
const kind = solution.kind;
|
||||
switch (kind.kind) {
|
||||
case "roots":
|
||||
if (kind.roots.length === 0) return "No real solution";
|
||||
return kind.roots.map((root) => `${solution.variable ?? "x"} = ${plain(root)}`).join(", ");
|
||||
case "identity":
|
||||
return "True for every value";
|
||||
case "contradiction":
|
||||
return "No solution";
|
||||
case "value":
|
||||
return plain(kind.value);
|
||||
case "simplified":
|
||||
return plain(kind.value);
|
||||
case "interval":
|
||||
return intervalText(kind.lower, kind.upper, kind.relation, solution.variable);
|
||||
}
|
||||
}
|
||||
|
||||
function intervalText(
|
||||
lower: MathExpression | null,
|
||||
upper: MathExpression | null,
|
||||
relation: MathRelation,
|
||||
variable: string | null,
|
||||
): string {
|
||||
const name = variable ?? "x";
|
||||
if (lower && !upper) return `${name} ${relation} ${plain(lower)}`;
|
||||
if (upper && !lower) return `${name} ${relation} ${plain(upper)}`;
|
||||
if (lower && upper) return `${plain(lower)} < ${name} < ${plain(upper)}`;
|
||||
return `all ${name}`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Solver
|
||||
|
||||
export function solve(
|
||||
expression: MathExpression,
|
||||
solveFor: string | null = null,
|
||||
context: EvaluatorContext = radiansContext(),
|
||||
): MathSolution {
|
||||
const steps = new SolutionStepRecorder();
|
||||
const simplified = simplify(expression);
|
||||
|
||||
if (simplified.type !== "relation") {
|
||||
return evaluateExpression(simplified, expression, context, steps);
|
||||
}
|
||||
|
||||
const relation = simplified.relation;
|
||||
const lhs = simplified.lhs;
|
||||
const rhs = simplified.rhs;
|
||||
|
||||
const variable = solveFor ?? variablesOf(simplified)[0] ?? null;
|
||||
if (!variable) {
|
||||
// No unknown: this is a claim to check, not an equation to solve.
|
||||
return checkClaim(relation, lhs, rhs, expression, context);
|
||||
}
|
||||
|
||||
steps.add("Start", simplified, `Solve for ${variable}.`);
|
||||
|
||||
// Move everything to the left: lhs - rhs (relation) 0.
|
||||
const difference = simplify(subtractExpr(lhs, rhs));
|
||||
if (!(rhs.type === "number" && isZero(rhs.value))) {
|
||||
steps.add(
|
||||
"Move every term to one side",
|
||||
relationExpr(relation, difference, ZERO),
|
||||
`Subtract ${plain(rhs)} from both sides.`,
|
||||
);
|
||||
}
|
||||
|
||||
const polynomial = Polynomial.extract(difference, variable);
|
||||
if (!polynomial) {
|
||||
return solveNumerically(difference, relation, variable, expression, context, steps);
|
||||
}
|
||||
|
||||
if (relation !== "=") {
|
||||
return solveInequality(polynomial, relation, variable, expression, steps);
|
||||
}
|
||||
|
||||
switch (polynomial.degree) {
|
||||
case 0: {
|
||||
// No unknown survived: either always true or never.
|
||||
const constant = polynomial.at(0);
|
||||
const kind: MathSolutionKind = isZero(constant) ? { kind: "identity" } : { kind: "contradiction" };
|
||||
steps.add(
|
||||
isZero(constant) ? "Every value works" : "No value works",
|
||||
relationExpr("=", num(constant), ZERO),
|
||||
isZero(constant)
|
||||
? `${variable} cancelled out and the statement is true.`
|
||||
: `${variable} cancelled out and ${describeNumber(constant)} ≠ 0.`,
|
||||
);
|
||||
return { kind, variable, steps: steps.steps, restatement: simplified };
|
||||
}
|
||||
|
||||
case 1:
|
||||
return solveLinear(polynomial, variable, simplified, steps);
|
||||
|
||||
case 2:
|
||||
return solveQuadratic(polynomial, variable, simplified, steps);
|
||||
|
||||
default:
|
||||
return solvePolynomial(polynomial, variable, simplified, steps);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plain expressions
|
||||
|
||||
function evaluateExpression(
|
||||
simplified: MathExpression,
|
||||
original: MathExpression,
|
||||
context: EvaluatorContext,
|
||||
steps: SolutionStepRecorder,
|
||||
): MathSolution {
|
||||
steps.add("Start", original, "Evaluate the expression.");
|
||||
if (!expressionEquals(simplified, original)) {
|
||||
steps.add("Simplify", simplified, "Combine like terms and constants.");
|
||||
}
|
||||
let value: MathNumber | null = null;
|
||||
try {
|
||||
value = evaluateExact(simplified, context);
|
||||
} catch {
|
||||
value = null;
|
||||
}
|
||||
if (value !== null) {
|
||||
const result = num(value);
|
||||
if (!expressionEquals(result, simplified)) {
|
||||
steps.add("Result", result, "Evaluate what is left.");
|
||||
}
|
||||
return { kind: { kind: "value", value: result }, variable: null, steps: steps.steps, restatement: original };
|
||||
}
|
||||
// Free variables remain — the best answer is the simplified form.
|
||||
return {
|
||||
kind: { kind: "simplified", value: simplified },
|
||||
variable: null,
|
||||
steps: steps.steps,
|
||||
restatement: original,
|
||||
};
|
||||
}
|
||||
|
||||
function checkClaim(
|
||||
relation: MathRelation,
|
||||
lhs: MathExpression,
|
||||
rhs: MathExpression,
|
||||
original: MathExpression,
|
||||
context: EvaluatorContext,
|
||||
): MathSolution {
|
||||
const steps = new SolutionStepRecorder();
|
||||
steps.add("Start", original, "Check whether this is true.");
|
||||
let left: MathNumber;
|
||||
let right: MathNumber;
|
||||
try {
|
||||
left = evaluateExact(lhs, context);
|
||||
right = evaluateExact(rhs, context);
|
||||
} catch {
|
||||
return {
|
||||
kind: { kind: "simplified", value: original },
|
||||
variable: null,
|
||||
steps: steps.steps,
|
||||
restatement: original,
|
||||
};
|
||||
}
|
||||
steps.add(
|
||||
"Evaluate both sides",
|
||||
relationExpr(relation, num(left), num(right)),
|
||||
`${describeNumber(left)} ${spokenRelation(relation)} ${describeNumber(right)}?`,
|
||||
);
|
||||
let holds: boolean;
|
||||
switch (relation) {
|
||||
case "=":
|
||||
holds = doubleValue(left) === doubleValue(right);
|
||||
break;
|
||||
case "<":
|
||||
holds = doubleValue(left) < doubleValue(right);
|
||||
break;
|
||||
case "<=":
|
||||
holds = doubleValue(left) <= doubleValue(right);
|
||||
break;
|
||||
case ">":
|
||||
holds = doubleValue(left) > doubleValue(right);
|
||||
break;
|
||||
case ">=":
|
||||
holds = doubleValue(left) >= doubleValue(right);
|
||||
break;
|
||||
}
|
||||
return {
|
||||
kind: holds ? { kind: "identity" } : { kind: "contradiction" },
|
||||
variable: null,
|
||||
steps: steps.steps,
|
||||
restatement: original,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Linear
|
||||
|
||||
function solveLinear(
|
||||
polynomial: Polynomial,
|
||||
variable: string,
|
||||
original: MathExpression,
|
||||
steps: SolutionStepRecorder,
|
||||
): MathSolution {
|
||||
const a = polynomial.at(1);
|
||||
const b = polynomial.at(0);
|
||||
steps.add(
|
||||
`Isolate the ${variable} term`,
|
||||
relationExpr("=", multiplyExpr([num(a), variableExpr(variable)]), num(negated(b))),
|
||||
`Move the constant across: ${renderNumber(a)}${variable} = ${renderNumber(negated(b))}.`,
|
||||
);
|
||||
const root = divideNumber(negated(b), a);
|
||||
const rootExpression = num(root);
|
||||
steps.add(
|
||||
`Divide by ${renderNumber(a)}`,
|
||||
relationExpr("=", variableExpr(variable), rootExpression),
|
||||
`${variable} = ${renderNumber(negated(b))} ÷ ${renderNumber(a)} = ${renderNumber(root)}.`,
|
||||
);
|
||||
return {
|
||||
kind: { kind: "roots", roots: [rootExpression] },
|
||||
variable,
|
||||
steps: steps.steps,
|
||||
restatement: original,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Quadratic
|
||||
|
||||
function solveQuadratic(
|
||||
polynomial: Polynomial,
|
||||
variable: string,
|
||||
original: MathExpression,
|
||||
steps: SolutionStepRecorder,
|
||||
): MathSolution {
|
||||
const a = polynomial.at(2);
|
||||
const b = polynomial.at(1);
|
||||
const c = polynomial.at(0);
|
||||
steps.add(
|
||||
"Read off the coefficients",
|
||||
polynomial.expression(),
|
||||
`a = ${renderNumber(a)}, b = ${renderNumber(b)}, c = ${renderNumber(c)}.`,
|
||||
);
|
||||
|
||||
const discriminant = subtract(multiply(b, b), multiply(multiply(integer(4), a), c));
|
||||
steps.add(
|
||||
"Discriminant",
|
||||
num(discriminant),
|
||||
`b² − 4ac = ${renderNumber(b)}² − 4·${renderNumber(a)}·${renderNumber(c)} = ${renderNumber(discriminant)}.`,
|
||||
);
|
||||
|
||||
if (isNegative(discriminant)) {
|
||||
steps.add(
|
||||
"No real roots",
|
||||
num(discriminant),
|
||||
"The discriminant is negative, so the parabola never crosses the axis.",
|
||||
);
|
||||
return { kind: { kind: "roots", roots: [] }, variable, steps: steps.steps, restatement: original };
|
||||
}
|
||||
|
||||
// Prefer an exact square root — it reads far better in a step-by-step than
|
||||
// the formula does, and it is what a person would do.
|
||||
const squareRoot = raisedTo(discriminant, rational(1, 2));
|
||||
const exactRoot = isExact(squareRoot);
|
||||
|
||||
if (isZero(discriminant)) {
|
||||
const root = divideNumber(negated(b), multiply(integer(2), a));
|
||||
steps.add(
|
||||
"One repeated root",
|
||||
relationExpr("=", variableExpr(variable), num(root)),
|
||||
`With a zero discriminant, ${variable} = −b / 2a = ${renderNumber(root)}.`,
|
||||
);
|
||||
return {
|
||||
kind: { kind: "roots", roots: [num(root)] },
|
||||
variable,
|
||||
steps: steps.steps,
|
||||
restatement: original,
|
||||
};
|
||||
}
|
||||
|
||||
steps.add(
|
||||
"Quadratic formula",
|
||||
relationExpr(
|
||||
"=",
|
||||
variableExpr(variable),
|
||||
divideExpr(addExpr([negate(num(b)), fn("sqrt", [num(discriminant)])]), multiplyExpr([int(2), num(a)])),
|
||||
),
|
||||
"x = (−b ± √(b² − 4ac)) / 2a.",
|
||||
);
|
||||
|
||||
const denominator = multiply(integer(2), a);
|
||||
let rootExpressions: MathExpression[];
|
||||
if (exactRoot) {
|
||||
const first = divideNumber(add(negated(b), squareRoot), denominator);
|
||||
const second = divideNumber(subtract(negated(b), squareRoot), denominator);
|
||||
const ordered = [first, second].sort((x, y) => doubleValue(x) - doubleValue(y));
|
||||
rootExpressions = ordered.map((value) => num(value));
|
||||
steps.add(
|
||||
"Exact roots",
|
||||
addExpr(rootExpressions),
|
||||
`√${renderNumber(discriminant)} = ${renderNumber(squareRoot)}, so the roots are exact.`,
|
||||
);
|
||||
} else {
|
||||
// Keep the surd symbolic: (−b ± √D) / 2a is the exact answer, and
|
||||
// collapsing it to decimals throws away information the wearer may want
|
||||
// to see.
|
||||
const surd = fn("sqrt", [num(discriminant)]);
|
||||
const plus = simplify(divideExpr(addExpr([num(negated(b)), surd]), num(denominator)));
|
||||
const minus = simplify(divideExpr(subtractExpr(num(negated(b)), surd), num(denominator)));
|
||||
rootExpressions = [plus, minus];
|
||||
const approximate: number[] = [];
|
||||
for (const root of rootExpressions) {
|
||||
try {
|
||||
approximate.push(doubleValue(evaluateExact(root)));
|
||||
} catch {
|
||||
// Leave it out of the approximation line.
|
||||
}
|
||||
}
|
||||
steps.add(
|
||||
"Roots",
|
||||
addExpr(rootExpressions),
|
||||
approximate.length === 2
|
||||
? `≈ ${formatApprox(approximate[0]!)} and ${formatApprox(approximate[1]!)}.`
|
||||
: "The discriminant is not a perfect square, so the roots keep their radical.",
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
kind: { kind: "roots", roots: rootExpressions },
|
||||
variable,
|
||||
steps: steps.steps,
|
||||
restatement: original,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Higher degree
|
||||
|
||||
function solvePolynomial(
|
||||
polynomial: Polynomial,
|
||||
variable: string,
|
||||
original: MathExpression,
|
||||
steps: SolutionStepRecorder,
|
||||
): MathSolution {
|
||||
steps.add(
|
||||
`Degree ${polynomial.degree} polynomial`,
|
||||
polynomial.expression(),
|
||||
"Look for rational roots, then solve what is left.",
|
||||
);
|
||||
|
||||
let remaining = polynomial;
|
||||
const found: MathNumber[] = [];
|
||||
|
||||
// Rational root theorem: p/q where p divides the constant term and q
|
||||
// divides the leading coefficient. Cheap, exact, and it usually cracks the
|
||||
// textbook cases outright.
|
||||
for (;;) {
|
||||
if (remaining.degree <= 2) break;
|
||||
const root = rationalRoot(remaining);
|
||||
if (!root) break;
|
||||
found.push(root);
|
||||
remaining = remaining.dividingByRoot(root);
|
||||
steps.add(
|
||||
`Factor out (${variable} − ${renderNumber(root)})`,
|
||||
remaining.expression(),
|
||||
`${variable} = ${renderNumber(root)} is a root; divide it out.`,
|
||||
);
|
||||
}
|
||||
|
||||
switch (remaining.degree) {
|
||||
case 1:
|
||||
found.push(divideNumber(negated(remaining.at(0)), remaining.at(1)));
|
||||
break;
|
||||
case 2: {
|
||||
const a = remaining.at(2);
|
||||
const b = remaining.at(1);
|
||||
const c = remaining.at(0);
|
||||
const discriminant = subtract(multiply(b, b), multiply(multiply(integer(4), a), c));
|
||||
if (!isNegative(discriminant)) {
|
||||
const squareRoot = raisedTo(discriminant, rational(1, 2));
|
||||
found.push(divideNumber(add(negated(b), squareRoot), multiply(integer(2), a)));
|
||||
if (!isZero(discriminant)) {
|
||||
found.push(divideNumber(subtract(negated(b), squareRoot), multiply(integer(2), a)));
|
||||
}
|
||||
}
|
||||
steps.add(
|
||||
"Solve the quadratic factor",
|
||||
remaining.expression(),
|
||||
"What is left is a quadratic; apply the formula.",
|
||||
);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
// No closed form available — find the real roots numerically.
|
||||
const numeric = numericRoots(remaining);
|
||||
found.push(...numeric.map((root) => fromDecimal(root)));
|
||||
steps.add(
|
||||
"Numeric roots",
|
||||
remaining.expression(),
|
||||
numeric.length === 0
|
||||
? "No further real roots were found."
|
||||
: "No exact factorisation remains, so the rest are found numerically.",
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const sorted = [...found].sort((x, y) => doubleValue(x) - doubleValue(y));
|
||||
return {
|
||||
kind: { kind: "roots", roots: sorted.map((value) => num(value)) },
|
||||
variable,
|
||||
steps: steps.steps,
|
||||
restatement: original,
|
||||
};
|
||||
}
|
||||
|
||||
export function rationalRoot(polynomial: Polynomial): MathNumber | null {
|
||||
const integers = polynomial.integerCoefficients;
|
||||
if (!integers) return null;
|
||||
const constant = integers[0];
|
||||
const leading = integers[integers.length - 1];
|
||||
if (!constant || !leading) return null;
|
||||
|
||||
const constantDivisors = divisorsOf(Math.abs(constant));
|
||||
const leadingDivisors = divisorsOf(Math.abs(leading));
|
||||
for (const p of constantDivisors) {
|
||||
for (const q of leadingDivisors) {
|
||||
for (const sign of [1, -1]) {
|
||||
const candidate = rational(sign * p, q);
|
||||
if (Math.abs(polynomial.value(doubleValue(candidate))) < 1e-9) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function divisorsOf(value: number): number[] {
|
||||
if (value <= 0 || value >= 1_000_000) return [1];
|
||||
const result: number[] = [];
|
||||
for (let candidate = 1; candidate * candidate <= value; candidate++) {
|
||||
if (value % candidate === 0) {
|
||||
result.push(candidate);
|
||||
if (candidate !== value / candidate) result.push(value / candidate);
|
||||
}
|
||||
}
|
||||
return result.sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bracket-and-bisect over a sampled range. Bisection rather than bare Newton
|
||||
* because Newton alone diverges on a bad seed, and a diverging solver on the
|
||||
* lens produces nonsense rather than nothing.
|
||||
*/
|
||||
export function numericRoots(
|
||||
polynomial: Polynomial,
|
||||
searchRange: [number, number] = [-1000, 1000],
|
||||
samples = 20_000,
|
||||
): number[] {
|
||||
if (polynomial.degree < 1) return [];
|
||||
const [lower, upper] = searchRange;
|
||||
const roots: number[] = [];
|
||||
const step = (upper - lower) / samples;
|
||||
let previousX = lower;
|
||||
let previousY = polynomial.value(previousX);
|
||||
|
||||
for (let index = 1; index <= samples; index++) {
|
||||
const x = lower + index * step;
|
||||
const y = polynomial.value(x);
|
||||
|
||||
if (y === 0) {
|
||||
roots.push(x);
|
||||
previousX = x;
|
||||
previousY = y;
|
||||
continue;
|
||||
}
|
||||
if (Math.sign(previousY) === Math.sign(y) || previousY === 0) {
|
||||
previousX = x;
|
||||
previousY = y;
|
||||
continue;
|
||||
}
|
||||
|
||||
let low = previousX;
|
||||
let high = x;
|
||||
for (let iteration = 0; iteration < 80; iteration++) {
|
||||
const mid = (low + high) / 2;
|
||||
const value = polynomial.value(mid);
|
||||
if (value === 0) {
|
||||
low = mid;
|
||||
high = mid;
|
||||
break;
|
||||
}
|
||||
if (Math.sign(value) === Math.sign(polynomial.value(low))) {
|
||||
low = mid;
|
||||
} else {
|
||||
high = mid;
|
||||
}
|
||||
}
|
||||
roots.push((low + high) / 2);
|
||||
previousX = x;
|
||||
previousY = y;
|
||||
}
|
||||
|
||||
// Collapse near-duplicates from adjacent brackets around a tangency.
|
||||
const unique: number[] = [];
|
||||
for (const root of roots.sort((a, b) => a - b)) {
|
||||
if (!unique.some((existing) => Math.abs(existing - root) < 1e-7)) {
|
||||
unique.push(root);
|
||||
}
|
||||
}
|
||||
return unique;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Inequalities
|
||||
|
||||
function solveInequality(
|
||||
polynomial: Polynomial,
|
||||
relation: MathRelation,
|
||||
variable: string,
|
||||
original: MathExpression,
|
||||
steps: SolutionStepRecorder,
|
||||
): MathSolution {
|
||||
if (polynomial.degree !== 1) {
|
||||
// Higher-degree inequalities need sign analysis across intervals; report
|
||||
// the roots rather than pretending to a full solution.
|
||||
const solution = solvePolynomial(polynomial, variable, original, steps);
|
||||
steps.add(
|
||||
"Critical points",
|
||||
polynomial.expression(),
|
||||
"The sign can only change at these values; test a point in each interval.",
|
||||
);
|
||||
return { kind: solution.kind, variable, steps: steps.steps, restatement: original };
|
||||
}
|
||||
|
||||
const a = polynomial.at(1);
|
||||
const b = polynomial.at(0);
|
||||
const bound = divideNumber(negated(b), a);
|
||||
// Dividing by a negative flips the inequality — the single most common
|
||||
// mistake in this whole topic, so it gets its own visible step.
|
||||
const finalRelation = isNegative(a) ? flippedRelation(relation) : relation;
|
||||
steps.add(
|
||||
`Divide by ${renderNumber(a)}`,
|
||||
relationExpr(finalRelation, variableExpr(variable), num(bound)),
|
||||
isNegative(a)
|
||||
? `Dividing by a negative flips the inequality to ${finalRelation}.`
|
||||
: `${variable} ${finalRelation} ${renderNumber(bound)}.`,
|
||||
);
|
||||
|
||||
const isUpperBound = finalRelation === "<" || finalRelation === "<=";
|
||||
return {
|
||||
kind: {
|
||||
kind: "interval",
|
||||
lower: isUpperBound ? null : num(bound),
|
||||
upper: isUpperBound ? num(bound) : null,
|
||||
relation: finalRelation,
|
||||
},
|
||||
variable,
|
||||
steps: steps.steps,
|
||||
restatement: original,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Non-polynomial
|
||||
|
||||
function solveNumerically(
|
||||
difference: MathExpression,
|
||||
relation: MathRelation,
|
||||
variable: string,
|
||||
original: MathExpression,
|
||||
context: EvaluatorContext,
|
||||
steps: SolutionStepRecorder,
|
||||
): MathSolution {
|
||||
steps.add(
|
||||
"Not a polynomial",
|
||||
difference,
|
||||
`${variable} appears inside a function, so the roots are found numerically.`,
|
||||
);
|
||||
let roots: number[] = [];
|
||||
const lower = -100;
|
||||
const upper = 100;
|
||||
const samples = 40_000;
|
||||
const step = (upper - lower) / samples;
|
||||
|
||||
const evaluate = (x: number): number | null =>
|
||||
evaluateValue(difference, { [variable]: x }, context.usesDegrees);
|
||||
|
||||
let previousX = lower;
|
||||
let previousY = evaluate(previousX);
|
||||
for (let index = 1; index <= samples; index++) {
|
||||
const x = lower + index * step;
|
||||
const y = evaluate(x);
|
||||
const lastX = previousX;
|
||||
const lastY = previousY;
|
||||
previousX = x;
|
||||
previousY = y;
|
||||
if (y === null || lastY === null) continue;
|
||||
// A sign change across a pole is not a root. Reject brackets where the
|
||||
// function magnitude explodes — that is `tan`'s asymptote, not a
|
||||
// crossing.
|
||||
if (Math.sign(lastY) === Math.sign(y)) continue;
|
||||
if (Math.abs(lastY) >= 1e6 || Math.abs(y) >= 1e6) continue;
|
||||
|
||||
let low = lastX;
|
||||
let high = x;
|
||||
for (let iteration = 0; iteration < 60; iteration++) {
|
||||
const mid = (low + high) / 2;
|
||||
const value = evaluate(mid);
|
||||
if (value === null) break;
|
||||
if (value === 0) {
|
||||
low = mid;
|
||||
high = mid;
|
||||
break;
|
||||
}
|
||||
const lowValue = evaluate(low);
|
||||
if (lowValue !== null && Math.sign(value) === Math.sign(lowValue)) {
|
||||
low = mid;
|
||||
} else {
|
||||
high = mid;
|
||||
}
|
||||
}
|
||||
const root = (low + high) / 2;
|
||||
// Verify the root rather than trusting the sign change.
|
||||
//
|
||||
// A sign change also happens across a pole — tan(x) flips from +∞ to −∞
|
||||
// at π/2 — and bisection happily converges onto the asymptote. The
|
||||
// magnitude guard above does not catch it, because a sample 0.0025 away
|
||||
// from the pole is only ~400, nowhere near the cutoff. At a real root the
|
||||
// residual is ~1e-15; at a pole it is enormous.
|
||||
const residual = evaluate(root);
|
||||
if (residual === null || Math.abs(residual) >= 1e-6) continue;
|
||||
if (!roots.some((existing) => Math.abs(existing - root) < 1e-6)) roots.push(root);
|
||||
}
|
||||
|
||||
// Keep the roots NEAREST ZERO, not the first twelve found.
|
||||
//
|
||||
// sin(x) = 0 has 64 roots in this window; scanning left to right and
|
||||
// stopping at twelve returned everything between −97 and −63 and nothing
|
||||
// near the origin, which is the opposite of what anyone asking
|
||||
// "solve sin x = 0" wants to see.
|
||||
const maximumRoots = 12;
|
||||
if (roots.length > maximumRoots) {
|
||||
roots = roots.sort((a, b) => Math.abs(a) - Math.abs(b)).slice(0, maximumRoots);
|
||||
}
|
||||
roots.sort((a, b) => a - b);
|
||||
|
||||
steps.add(
|
||||
"Roots found",
|
||||
difference,
|
||||
roots.length === 0
|
||||
? "No sign change was found between −100 and 100."
|
||||
: "Searched between −100 and 100 for sign changes.",
|
||||
);
|
||||
return {
|
||||
kind: { kind: "roots", roots: roots.map((root) => num(fromDecimal(root))) },
|
||||
variable,
|
||||
steps: steps.steps,
|
||||
restatement: original,
|
||||
};
|
||||
}
|
||||
|
||||
function formatApprox(value: number): string {
|
||||
return describeNumber(real(value));
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
// Symbolic antiderivatives. Not a Risch implementation — that is a
|
||||
// research-grade algorithm and wildly out of proportion here. This is the
|
||||
// standard table plus three structural rules (linearity, linear substitution,
|
||||
// integration by parts), which is what actually covers a calculus course.
|
||||
// Anything outside that returns null rather than a wrong answer, and the
|
||||
// caller falls back to the numeric integrator, which always works.
|
||||
|
||||
import {
|
||||
type MathExpression,
|
||||
addExpr,
|
||||
divideExpr,
|
||||
fn,
|
||||
int,
|
||||
multiplyExpr,
|
||||
negate,
|
||||
num,
|
||||
numberValue,
|
||||
powerExpr,
|
||||
subtractExpr,
|
||||
variable as variableExpr,
|
||||
variablesOf,
|
||||
} from "./expression";
|
||||
import {
|
||||
type MathNumber,
|
||||
add,
|
||||
fromDecimal,
|
||||
integer,
|
||||
multiply,
|
||||
numberEquals,
|
||||
rational,
|
||||
reciprocal,
|
||||
} from "./math-number";
|
||||
import { simplify } from "./simplifier";
|
||||
import { differentiate, integrateNumeric } from "./derivative";
|
||||
import { evaluateValue } from "./evaluator";
|
||||
import { Polynomial } from "./polynomial";
|
||||
import { isZero } from "./math-number";
|
||||
|
||||
/** Indefinite integral with respect to `variable`, without the constant. */
|
||||
export function integrate(expression: MathExpression, variable: string): MathExpression | null {
|
||||
const raw = attempt(simplify(expression), variable, 0);
|
||||
if (!raw) return null;
|
||||
return simplify(raw);
|
||||
}
|
||||
|
||||
/** With `+ C`, for display. */
|
||||
export function integrateWithConstant(expression: MathExpression, variable: string): MathExpression | null {
|
||||
const result = integrate(expression, variable);
|
||||
return result ? addExpr([result, variableExpr("C")]) : null;
|
||||
}
|
||||
|
||||
function attempt(expression: MathExpression, variable: string, depth: number): MathExpression | null {
|
||||
// Integration by parts can recurse; bound it so a bad pairing cannot loop
|
||||
// forever.
|
||||
if (depth >= 6) return null;
|
||||
|
||||
// Constant with respect to the variable: ∫c dx = cx
|
||||
if (!variablesOf(expression).includes(variable)) {
|
||||
return multiplyExpr([expression, variableExpr(variable)]);
|
||||
}
|
||||
|
||||
switch (expression.type) {
|
||||
case "variable":
|
||||
if (expression.name === variable) {
|
||||
return divideExpr(powerExpr(variableExpr(variable), int(2)), int(2));
|
||||
}
|
||||
// A variable other than the integration variable is already handled by
|
||||
// the constant guard above; nothing reaches here.
|
||||
return null;
|
||||
|
||||
case "negate": {
|
||||
const inner = attempt(expression.inner, variable, depth);
|
||||
return inner ? negate(inner) : null;
|
||||
}
|
||||
|
||||
case "add": {
|
||||
// Linearity. If any term is not integrable the whole thing is not.
|
||||
const integrated: MathExpression[] = [];
|
||||
for (const term of expression.terms) {
|
||||
const part = attempt(term, variable, depth);
|
||||
if (!part) return null;
|
||||
integrated.push(part);
|
||||
}
|
||||
return addExpr(integrated);
|
||||
}
|
||||
|
||||
case "multiply":
|
||||
return integrateProduct(expression.factors, variable, depth);
|
||||
|
||||
case "power":
|
||||
return integratePower(expression.base, expression.exponent, variable);
|
||||
|
||||
case "function": {
|
||||
const argument = expression.args[0];
|
||||
if (!argument) return null;
|
||||
return integrateFunction(expression.fn, argument, variable);
|
||||
}
|
||||
|
||||
case "number":
|
||||
case "constant":
|
||||
case "relation":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Products
|
||||
|
||||
function integrateProduct(
|
||||
factors: MathExpression[],
|
||||
variable: string,
|
||||
depth: number,
|
||||
): MathExpression | null {
|
||||
// Pull constants out front: ∫ c·f dx = c·∫f dx
|
||||
const constants: MathExpression[] = [];
|
||||
const variableFactors: MathExpression[] = [];
|
||||
for (const factor of factors) {
|
||||
if (variablesOf(factor).includes(variable)) {
|
||||
variableFactors.push(factor);
|
||||
} else {
|
||||
constants.push(factor);
|
||||
}
|
||||
}
|
||||
if (variableFactors.length === 0) {
|
||||
return multiplyExpr([...factors, variableExpr(variable)]);
|
||||
}
|
||||
if (constants.length > 0) {
|
||||
const inner = variableFactors.length === 1 ? variableFactors[0]! : multiplyExpr(variableFactors);
|
||||
const integrated = attempt(inner, variable, depth);
|
||||
if (!integrated) return null;
|
||||
return multiplyExpr([...constants, integrated]);
|
||||
}
|
||||
if (variableFactors.length !== 2) return null;
|
||||
return integrateByParts(variableFactors[0]!, variableFactors[1]!, variable, depth);
|
||||
}
|
||||
|
||||
/**
|
||||
* ∫u dv = uv − ∫v du.
|
||||
*
|
||||
* Picks `u` by the LIATE heuristic: whichever factor differentiates toward
|
||||
* nothing goes in `u`. Getting this backwards turns a one-step integral into
|
||||
* an infinite regress, which is why the depth bound above exists.
|
||||
*/
|
||||
function integrateByParts(
|
||||
first: MathExpression,
|
||||
second: MathExpression,
|
||||
variable: string,
|
||||
depth: number,
|
||||
): MathExpression | null {
|
||||
const priority = (expression: MathExpression): number => {
|
||||
if (expression.type === "function") {
|
||||
switch (expression.fn) {
|
||||
case "ln":
|
||||
case "log10":
|
||||
case "log2":
|
||||
return 5;
|
||||
case "asin":
|
||||
case "acos":
|
||||
case "atan":
|
||||
return 4;
|
||||
case "sin":
|
||||
case "cos":
|
||||
case "tan":
|
||||
return 2;
|
||||
case "exp":
|
||||
return 1;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if (expression.type === "variable" || expression.type === "power") return 3;
|
||||
return 0;
|
||||
};
|
||||
|
||||
const [u, dv] = priority(first) >= priority(second) ? [first, second] : [second, first];
|
||||
|
||||
const v = attempt(dv, variable, depth + 1);
|
||||
if (!v) return null;
|
||||
const du = differentiate(u, variable);
|
||||
const remainder = simplify(multiplyExpr([v, du]));
|
||||
const integratedRemainder = attempt(remainder, variable, depth + 1);
|
||||
if (!integratedRemainder) return null;
|
||||
return subtractExpr(multiplyExpr([u, v]), integratedRemainder);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Powers
|
||||
|
||||
function integratePower(
|
||||
base: MathExpression,
|
||||
exponent: MathExpression,
|
||||
variable: string,
|
||||
): MathExpression | null {
|
||||
const baseHasVariable = variablesOf(base).includes(variable);
|
||||
const exponentHasVariable = variablesOf(exponent).includes(variable);
|
||||
|
||||
// Exponential: ∫a^x dx = a^x / ln a
|
||||
if (!baseHasVariable && exponentHasVariable) {
|
||||
const linear = linearForm(exponent, variable);
|
||||
if (!linear) return null;
|
||||
const antiderivative = divideExpr(powerExpr(base, exponent), fn("ln", [base]));
|
||||
return divideExpr(antiderivative, num(linear.slope));
|
||||
}
|
||||
|
||||
if (!baseHasVariable || exponentHasVariable) return null;
|
||||
const power = numberValue(exponent);
|
||||
if (!power) return null;
|
||||
|
||||
// Chain rule in reverse, but only for a LINEAR inner function. For a
|
||||
// nonlinear inner function the substitution needs its own du, which this
|
||||
// level of machinery cannot supply — returning null there is the
|
||||
// difference between "no symbolic form" and a wrong one.
|
||||
const linear = linearForm(base, variable);
|
||||
if (!linear) return null;
|
||||
|
||||
// ∫(ax+b)^-1 dx = ln|ax+b| / a
|
||||
if (numberEquals(power, integer(-1))) {
|
||||
return divideExpr(fn("ln", [fn("abs", [base])]), num(linear.slope));
|
||||
}
|
||||
const raised = add(power, integer(1));
|
||||
return divideExpr(powerExpr(base, num(raised)), num(multiply(raised, linear.slope)));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Functions
|
||||
|
||||
function integrateFunction(
|
||||
functionName: string,
|
||||
argument: MathExpression,
|
||||
variable: string,
|
||||
): MathExpression | null {
|
||||
// Same restriction as powers: the inner function must be linear, or the
|
||||
// substitution is not this simple.
|
||||
const linear = linearForm(argument, variable);
|
||||
if (!linear) return null;
|
||||
const scale = num(reciprocal(linear.slope));
|
||||
|
||||
let antiderivative: MathExpression | null;
|
||||
switch (functionName) {
|
||||
case "sin":
|
||||
antiderivative = negate(fn("cos", [argument]));
|
||||
break;
|
||||
case "cos":
|
||||
antiderivative = fn("sin", [argument]);
|
||||
break;
|
||||
case "tan":
|
||||
antiderivative = negate(fn("ln", [fn("abs", [fn("cos", [argument])])]));
|
||||
break;
|
||||
case "exp":
|
||||
antiderivative = fn("exp", [argument]);
|
||||
break;
|
||||
case "sinh":
|
||||
antiderivative = fn("cosh", [argument]);
|
||||
break;
|
||||
case "cosh":
|
||||
antiderivative = fn("sinh", [argument]);
|
||||
break;
|
||||
case "ln":
|
||||
// ∫ln(u) du = u·ln(u) − u
|
||||
antiderivative = subtractExpr(multiplyExpr([argument, fn("ln", [argument])]), argument);
|
||||
break;
|
||||
case "sqrt":
|
||||
// ∫√u du = (2/3)·u^(3/2)
|
||||
antiderivative = multiplyExpr([num(rational(2, 3)), powerExpr(argument, num(rational(3, 2)))]);
|
||||
break;
|
||||
default:
|
||||
antiderivative = null;
|
||||
break;
|
||||
}
|
||||
if (!antiderivative) return null;
|
||||
return multiplyExpr([scale, antiderivative]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Definite
|
||||
|
||||
export type DefiniteResult =
|
||||
/** Evaluated from an exact antiderivative — the fundamental theorem. */
|
||||
| { kind: "exact"; value: MathNumber; antiderivative: MathExpression }
|
||||
/** No symbolic form; the value came from adaptive Simpson. */
|
||||
| { kind: "numeric"; value: number }
|
||||
| { kind: "failed"; reason: string };
|
||||
|
||||
/**
|
||||
* Prefer the symbolic route so the answer can show its working, and fall
|
||||
* back to numerics so the question always gets answered.
|
||||
*/
|
||||
export function definite(
|
||||
expression: MathExpression,
|
||||
variable: string,
|
||||
lower: number,
|
||||
upper: number,
|
||||
): DefiniteResult {
|
||||
const antiderivative = integrate(expression, variable);
|
||||
if (antiderivative) {
|
||||
const atUpper = evaluateValue(antiderivative, { [variable]: upper });
|
||||
const atLower = evaluateValue(antiderivative, { [variable]: lower });
|
||||
if (atUpper !== null && atLower !== null && Number.isFinite(atUpper) && Number.isFinite(atLower)) {
|
||||
return { kind: "exact", value: fromDecimal(atUpper - atLower), antiderivative };
|
||||
}
|
||||
}
|
||||
const value = integrateNumeric(expression, variable, lower, upper);
|
||||
if (value === null) {
|
||||
return { kind: "failed", reason: "The function is undefined somewhere in that range" };
|
||||
}
|
||||
return { kind: "numeric", value };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Linear form
|
||||
|
||||
/**
|
||||
* Recognises `a·x + b`, which is the only inner function the substitution
|
||||
* rules above can undo.
|
||||
*/
|
||||
export function linearForm(
|
||||
expression: MathExpression,
|
||||
variable: string,
|
||||
): { slope: MathNumber; intercept: MathNumber } | null {
|
||||
const polynomial = Polynomial.extract(expression, variable);
|
||||
if (!polynomial || polynomial.degree !== 1 || isZero(polynomial.at(1))) return null;
|
||||
return { slope: polynomial.at(1), intercept: polynomial.at(0) };
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
// The glasses have no formula renderer and a 576-pixel-wide window, so every
|
||||
// expression needs a compact ASCII form. Two things make this more than a
|
||||
// tree walk. First, the internal representation is deliberately uniform —
|
||||
// division is `a · b^-1`, subtraction is `a + (−b)` — and printing that
|
||||
// literally would produce `2*x^-1` where a reader expects `2/x`, so the
|
||||
// renderer detects those patterns and un-normalises them. Second, precedence
|
||||
// decides bracketing: too few brackets is wrong, too many is unreadable.
|
||||
|
||||
import { type MathExpression, numberValue } from "./expression";
|
||||
import { type MathNumber, describeNumber, isNegative, isOne, negated } from "./math-number";
|
||||
|
||||
const PRECEDENCE = {
|
||||
relation: 1,
|
||||
sum: 2,
|
||||
product: 3,
|
||||
power: 4,
|
||||
} as const;
|
||||
|
||||
export function plain(expression: MathExpression): string {
|
||||
return render(expression, 0);
|
||||
}
|
||||
|
||||
export function renderNumber(value: MathNumber): string {
|
||||
return describeNumber(value);
|
||||
}
|
||||
|
||||
function render(expression: MathExpression, parentPrecedence: number): string {
|
||||
switch (expression.type) {
|
||||
case "number": {
|
||||
const text = describeNumber(expression.value);
|
||||
return wrap(text, isNegative(expression.value) && parentPrecedence >= PRECEDENCE.product);
|
||||
}
|
||||
|
||||
case "variable":
|
||||
return expression.name;
|
||||
|
||||
case "constant":
|
||||
return expression.constant;
|
||||
|
||||
case "negate":
|
||||
return wrap("-" + render(expression.inner, PRECEDENCE.product), parentPrecedence > PRECEDENCE.sum);
|
||||
|
||||
case "add": {
|
||||
let output = "";
|
||||
for (let index = 0; index < expression.terms.length; index++) {
|
||||
const term = expression.terms[index]!;
|
||||
if (term.type === "negate") {
|
||||
output += index === 0 ? "-" : " - ";
|
||||
output += render(term.inner, PRECEDENCE.sum);
|
||||
continue;
|
||||
}
|
||||
const value = numberValue(term);
|
||||
if (value && isNegative(value) && index > 0) {
|
||||
output += " - " + describeNumber(negated(value));
|
||||
continue;
|
||||
}
|
||||
if (index > 0) output += " + ";
|
||||
output += render(term, PRECEDENCE.sum);
|
||||
}
|
||||
return wrap(output, parentPrecedence > PRECEDENCE.sum);
|
||||
}
|
||||
|
||||
case "multiply": {
|
||||
const numerator: MathExpression[] = [];
|
||||
const denominator: MathExpression[] = [];
|
||||
for (const factor of expression.factors) {
|
||||
if (factor.type === "power") {
|
||||
const power = numberValue(factor.exponent);
|
||||
if (power && isNegative(power)) {
|
||||
const positive = negated(power);
|
||||
denominator.push(
|
||||
isOne(positive) ? factor.base : { type: "power", base: factor.base, exponent: { type: "number", value: positive } },
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
numerator.push(factor);
|
||||
}
|
||||
const top =
|
||||
numerator.length === 0
|
||||
? "1"
|
||||
: numerator.map((factor) => render(factor, PRECEDENCE.product)).join("*");
|
||||
if (denominator.length === 0) {
|
||||
return wrap(top, parentPrecedence > PRECEDENCE.product);
|
||||
}
|
||||
const bottom = denominator.map((factor) => render(factor, PRECEDENCE.power)).join("*");
|
||||
return wrap(`${top}/${bottom}`, parentPrecedence > PRECEDENCE.product);
|
||||
}
|
||||
|
||||
case "power": {
|
||||
const exponentValue = numberValue(expression.exponent);
|
||||
if (exponentValue && exponentValue.kind === "rational" && exponentValue.n === 1 && exponentValue.d === 2) {
|
||||
return `sqrt(${render(expression.base, 0)})`;
|
||||
}
|
||||
// A bare negative power is a reciprocal. Printing `x^(-1)` where a
|
||||
// reader expects `1/x` is the plain-text twin of the fraction
|
||||
// un-normalisation above.
|
||||
if (exponentValue && isNegative(exponentValue)) {
|
||||
const positive = negated(exponentValue);
|
||||
const inner = isOne(positive)
|
||||
? render(expression.base, PRECEDENCE.power)
|
||||
: `${render(expression.base, PRECEDENCE.power + 1)}^${describeNumber(positive)}`;
|
||||
return wrap(`1/${inner}`, parentPrecedence > PRECEDENCE.product);
|
||||
}
|
||||
const body =
|
||||
`${render(expression.base, PRECEDENCE.power + 1)}` +
|
||||
`^${render(expression.exponent, PRECEDENCE.power + 1)}`;
|
||||
return wrap(body, parentPrecedence > PRECEDENCE.power);
|
||||
}
|
||||
|
||||
case "function": {
|
||||
const inner = expression.args.map((argument) => render(argument, 0)).join(", ");
|
||||
if (expression.fn === "factorial") return `(${inner})!`;
|
||||
if (expression.fn === "abs") return `|${inner}|`;
|
||||
return `${expression.fn}(${inner})`;
|
||||
}
|
||||
|
||||
case "relation":
|
||||
return (
|
||||
`${render(expression.lhs, PRECEDENCE.relation)} ` +
|
||||
`${expression.relation} ` +
|
||||
`${render(expression.rhs, PRECEDENCE.relation)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function wrap(body: string, condition: boolean): string {
|
||||
return condition ? `(${body})` : body;
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
// Trig equation solving and the identity sheet. The distinguishing feature
|
||||
// versus the generic numeric root finder: a trig equation has infinitely many
|
||||
// solutions, and the right answer is the FAMILY (`x = π/6 + 2πn`), not the
|
||||
// twelve roots that happen to fall in the search window. Reporting a finite
|
||||
// list for `sin x = 1/2` is the standard wrong answer in this topic.
|
||||
|
||||
import {
|
||||
type MathExpression,
|
||||
ZERO,
|
||||
constant,
|
||||
divideExpr,
|
||||
int,
|
||||
multiplyExpr,
|
||||
} from "./expression";
|
||||
import { describeNumber, fromDecimal } from "./math-number";
|
||||
import { plain } from "./text-renderer";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Solutions
|
||||
|
||||
/** One family of solutions: `base + period·n`. */
|
||||
export type SolutionFamily = {
|
||||
base: number;
|
||||
period: number;
|
||||
/** Exact form when the base is a recognisable multiple of π. */
|
||||
baseExpression: MathExpression | null;
|
||||
};
|
||||
|
||||
export function familyValues(family: SolutionFamily, lower: number, upper: number): number[] {
|
||||
if (family.period <= 0) {
|
||||
return family.base >= lower && family.base <= upper ? [family.base] : [];
|
||||
}
|
||||
const results: number[] = [];
|
||||
let n = Math.floor((lower - family.base) / family.period);
|
||||
for (;;) {
|
||||
const value = family.base + n * family.period;
|
||||
if (value > upper) break;
|
||||
if (value >= lower) results.push(value);
|
||||
n += 1;
|
||||
if (results.length > 1000) break;
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
export function familyText(family: SolutionFamily): string {
|
||||
const baseText = family.baseExpression
|
||||
? plain(family.baseExpression)
|
||||
: describeNumber(fromDecimal(family.base));
|
||||
// The separator is load-bearing: "2*pi" run straight into the index reads
|
||||
// as "2*pin", a different and nonsensical expression to anyone scanning it
|
||||
// on the lens.
|
||||
const periodText = describePi(family.period);
|
||||
return `${baseText} + ${periodText}·n`;
|
||||
}
|
||||
|
||||
export type SolutionSet =
|
||||
| { kind: "families"; families: SolutionFamily[] }
|
||||
| { kind: "all" }
|
||||
| { kind: "none" };
|
||||
|
||||
/** Solve `f(x) = value` for sin, cos, or tan. */
|
||||
export function solveTrig(functionName: "sin" | "cos" | "tan", value: number): SolutionSet {
|
||||
switch (functionName) {
|
||||
case "sin": {
|
||||
if (Math.abs(value) > 1) return { kind: "none" };
|
||||
const principal = Math.asin(value);
|
||||
// sin has two families per period, which collapse to one when the value
|
||||
// is ±1 (the turning points).
|
||||
if (Math.abs(Math.abs(value) - 1) < 1e-12) {
|
||||
return { kind: "families", families: [family(principal, 2 * Math.PI)] };
|
||||
}
|
||||
return {
|
||||
kind: "families",
|
||||
families: [family(principal, 2 * Math.PI), family(Math.PI - principal, 2 * Math.PI)],
|
||||
};
|
||||
}
|
||||
|
||||
case "cos": {
|
||||
if (Math.abs(value) > 1) return { kind: "none" };
|
||||
const principal = Math.acos(value);
|
||||
if (Math.abs(principal) < 1e-12 || Math.abs(principal - Math.PI) < 1e-12) {
|
||||
return { kind: "families", families: [family(principal, 2 * Math.PI)] };
|
||||
}
|
||||
return {
|
||||
kind: "families",
|
||||
families: [family(principal, 2 * Math.PI), family(-principal, 2 * Math.PI)],
|
||||
};
|
||||
}
|
||||
|
||||
case "tan":
|
||||
// tan repeats every π, not 2π — one family covers everything.
|
||||
return { kind: "families", families: [family(Math.atan(value), Math.PI)] };
|
||||
}
|
||||
}
|
||||
|
||||
function family(base: number, period: number): SolutionFamily {
|
||||
return { base, period, baseExpression: piMultiple(base) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Recognise a value as an exact rational multiple of π, so a solution reads
|
||||
* `π/6` instead of `0.5235987755982988`.
|
||||
*/
|
||||
export function piMultiple(value: number): MathExpression | null {
|
||||
if (!Number.isFinite(value)) return null;
|
||||
if (Math.abs(value) < 1e-12) return ZERO;
|
||||
const ratio = value / Math.PI;
|
||||
for (const denominator of [1, 2, 3, 4, 6, 8, 12]) {
|
||||
const scaled = ratio * denominator;
|
||||
const rounded = Math.round(scaled);
|
||||
if (Math.abs(scaled - rounded) >= 1e-9 || Math.abs(rounded) >= 1e6) continue;
|
||||
const numerator = rounded;
|
||||
if (numerator === 0) return ZERO;
|
||||
if (numerator === 1 && denominator === 1) return constant("pi");
|
||||
// pi/6, not (1/6)*pi — a unit numerator belongs in the fraction, which is
|
||||
// how every textbook writes these solution families.
|
||||
if (numerator === 1) return divideExpr(constant("pi"), int(denominator));
|
||||
if (denominator === 1) return multiplyExpr([int(numerator), constant("pi")]);
|
||||
return divideExpr(multiplyExpr([int(numerator), constant("pi")]), int(denominator));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function describePi(value: number): string {
|
||||
const multiple = piMultiple(value);
|
||||
return multiple ? plain(multiple) : describeNumber(fromDecimal(value));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Identities
|
||||
|
||||
export type TrigIdentity = {
|
||||
name: string;
|
||||
plain: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The identity sheet, for the "explain it" surface and for a wearer who
|
||||
* wants the reference on the lens.
|
||||
*/
|
||||
export const TRIG_IDENTITIES: readonly TrigIdentity[] = [
|
||||
{ name: "Pythagorean", plain: "sin²θ + cos²θ = 1" },
|
||||
{ name: "Pythagorean (tan)", plain: "1 + tan²θ = sec²θ" },
|
||||
{ name: "Sine sum", plain: "sin(a ± b) = sin a cos b ± cos a sin b" },
|
||||
{ name: "Cosine sum", plain: "cos(a ± b) = cos a cos b ∓ sin a sin b" },
|
||||
{ name: "Tangent sum", plain: "tan(a ± b) = (tan a ± tan b) / (1 ∓ tan a tan b)" },
|
||||
{ name: "Double angle (sine)", plain: "sin 2θ = 2 sin θ cos θ" },
|
||||
{ name: "Double angle (cosine)", plain: "cos 2θ = cos²θ − sin²θ = 2cos²θ − 1" },
|
||||
{ name: "Half angle", plain: "sin²θ = (1 − cos 2θ)/2" },
|
||||
{ name: "Law of sines", plain: "a/sin A = b/sin B = c/sin C" },
|
||||
{ name: "Law of cosines", plain: "c² = a² + b² − 2ab cos C" },
|
||||
];
|
||||
|
||||
export function identityMatching(query: string): TrigIdentity | null {
|
||||
const needle = query.toLowerCase();
|
||||
return (
|
||||
TRIG_IDENTITIES.find((identity) => identity.name.toLowerCase().includes(needle)) ??
|
||||
TRIG_IDENTITIES.find((identity) => needle.includes(identity.name.toLowerCase())) ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Conversion
|
||||
|
||||
export function degreesFromRadians(radians: number): number {
|
||||
return (radians * 180) / Math.PI;
|
||||
}
|
||||
|
||||
export function radiansFromDegrees(degrees: number): number {
|
||||
return (degrees * Math.PI) / 180;
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
// Workload estimation and routing for heavy maths requests.
|
||||
//
|
||||
// The router collapses to two honest options: the fast on-device answer, and an
|
||||
// explicit, cancellable long run on the phone that the wearer opts into.
|
||||
// The estimate is the whole point — every workload carries a closed-form
|
||||
// cost model so the offer can price the wait before doing any work.
|
||||
|
||||
import {
|
||||
type ComputeCancellation,
|
||||
type ComputeProgress,
|
||||
type MathConstantName,
|
||||
MAXIMUM_COMPUTED_DIGITS,
|
||||
MAXIMUM_FEASIBLE_DIGITS,
|
||||
NEVER_CANCELLED,
|
||||
constantSpokenName,
|
||||
deepFractionalDigits,
|
||||
} from "./constant-digits";
|
||||
import {
|
||||
type DigitCountResult,
|
||||
type DigitSearchOutcome,
|
||||
countInExpansion,
|
||||
locateDigits,
|
||||
} from "./digit-search";
|
||||
import { formatInt } from "./math-number";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Durations
|
||||
|
||||
/**
|
||||
* Turns a seconds estimate into something worth reading out. Deliberately
|
||||
* coarse: the cost model behind these numbers is accurate to an order of
|
||||
* magnitude, not to the second, so "about 247 seconds" would be a precision
|
||||
* the estimate does not have.
|
||||
*/
|
||||
export function describeDuration(seconds: number): string {
|
||||
if (!Number.isFinite(seconds) || seconds <= 0) return "no time at all";
|
||||
if (seconds < 1) return "under a second";
|
||||
if (seconds < 10) return `about ${Math.round(seconds)} seconds`;
|
||||
if (seconds < 60) return `about ${roundedTo(seconds, 5)} seconds`;
|
||||
|
||||
const minutes = seconds / 60;
|
||||
if (minutes < 2) return "about a minute and a half";
|
||||
if (minutes < 60) return `about ${Math.round(minutes)} minutes`;
|
||||
|
||||
const hours = minutes / 60;
|
||||
if (hours < 2) return "about an hour and a half";
|
||||
if (hours < 24) return `about ${Math.round(hours)} hours`;
|
||||
|
||||
const days = hours / 24;
|
||||
if (days < 365) return `about ${Math.round(days)} days`;
|
||||
const years = days / 365;
|
||||
return years < 2 ? "well over a year" : `about ${Math.round(years)} years`;
|
||||
}
|
||||
|
||||
/** Short form for the lens, where there is no room for a sentence. */
|
||||
export function compactDuration(seconds: number): string {
|
||||
if (!Number.isFinite(seconds) || seconds <= 0) return "0s";
|
||||
if (seconds < 60) return `${Math.round(seconds)}s`;
|
||||
if (seconds < 3600) return `${Math.round(seconds / 60)}m`;
|
||||
if (seconds < 86_400) return `${Math.round(seconds / 3600)}h`;
|
||||
return `${Math.round(seconds / 86_400)}d`;
|
||||
}
|
||||
|
||||
function roundedTo(value: number, step: number): number {
|
||||
return Math.max(step, Math.round(value / step) * step);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Workloads
|
||||
|
||||
export type MathWorkload =
|
||||
/** Generate the decimal expansion of a constant. */
|
||||
| { kind: "constantDigits"; constant: MathConstantName; count: number }
|
||||
/** Find a digit run inside a constant's expansion. */
|
||||
| { kind: "digitSearch"; constant: MathConstantName; pattern: string; occurrence: number }
|
||||
/** Count a digit run across the deepest available expansion. */
|
||||
| { kind: "digitCount"; constant: MathConstantName; pattern: string };
|
||||
|
||||
/**
|
||||
* Rough seconds on the phone. Machin with scalar big arithmetic is O(n²);
|
||||
* measured with V8 BigInt: 10,000 digits ≈ 0.06 s on an M-class core, so
|
||||
* ~0.35 s per (n/10k)² on a device-class core. It does not need to be
|
||||
* precise, only right about the ORDER OF MAGNITUDE, because the routing
|
||||
* threshold and the offers are separated by factors of thousands — and at
|
||||
* this value an hour reaches about a million digits, which is where any
|
||||
* five-digit run and most six-digit ones live.
|
||||
*/
|
||||
const SECONDS_PER_TEN_K_SQUARED = 0.35;
|
||||
|
||||
export function estimatedLocalSeconds(workload: MathWorkload): number {
|
||||
switch (workload.kind) {
|
||||
case "constantDigits": {
|
||||
const n = Math.max(workload.count, 1);
|
||||
return SECONDS_PER_TEN_K_SQUARED * (n / 10_000) * (n / 10_000);
|
||||
}
|
||||
case "digitSearch":
|
||||
// Dominated by generating enough digits to have a hope of finding the
|
||||
// run: a k-digit pattern first appears around 10^k places.
|
||||
return estimatedLocalSeconds({
|
||||
kind: "constantDigits",
|
||||
constant: workload.constant,
|
||||
count: expectedDepth(workload.pattern.length),
|
||||
});
|
||||
case "digitCount":
|
||||
return estimatedLocalSeconds({
|
||||
kind: "constantDigits",
|
||||
constant: workload.constant,
|
||||
count: expectedDepth(workload.pattern.length),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How many decimal places the workload would have to reach to answer
|
||||
* properly, as opposed to however few it settled for.
|
||||
*/
|
||||
export function requiredDepth(workload: MathWorkload): number {
|
||||
switch (workload.kind) {
|
||||
case "constantDigits":
|
||||
return Math.max(workload.count, 1);
|
||||
case "digitSearch":
|
||||
// The n-th occurrence sits roughly n× as deep as the first.
|
||||
return expectedDepth(workload.pattern.length) * Math.max(workload.occurrence, 1);
|
||||
case "digitCount":
|
||||
return expectedDepth(workload.pattern.length);
|
||||
}
|
||||
}
|
||||
|
||||
/** Roughly where a random run of `length` digits first appears. */
|
||||
export function expectedDepth(patternLength: number): number {
|
||||
if (patternLength <= 0) return 1_000;
|
||||
// Cap so the estimator does not overflow on a silly pattern.
|
||||
const bounded = Math.min(patternLength, 12);
|
||||
return Math.max(Math.pow(10, bounded), 1_000);
|
||||
}
|
||||
|
||||
export function describeWorkload(workload: MathWorkload): string {
|
||||
switch (workload.kind) {
|
||||
case "constantDigits":
|
||||
return `${formatInt(workload.count)} digits of ${constantSpokenName(workload.constant)}`;
|
||||
case "digitSearch":
|
||||
return `searching ${constantSpokenName(workload.constant)} for ${workload.pattern}`;
|
||||
case "digitCount":
|
||||
return `counting ${workload.pattern} in ${constantSpokenName(workload.constant)}`;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Offers
|
||||
|
||||
/**
|
||||
* An offer to grind the full-depth answer out on the phone. Produced when a
|
||||
* question needs a deeper expansion than the fast path holds. It is a value,
|
||||
* not an action: nothing runs until the caller accepts it, because the whole
|
||||
* point is that the wearer decides whether the wait is affordable right now.
|
||||
*/
|
||||
export type LongRunOffer = {
|
||||
/** What would be run. */
|
||||
workload: MathWorkload;
|
||||
/** The phone's own estimate for the full-depth run. */
|
||||
estimatedSeconds: number;
|
||||
/** Why the fast path could not settle it. */
|
||||
reason: string;
|
||||
/** How deep the run would go — digits, for the expansion workloads. */
|
||||
depth: number;
|
||||
/**
|
||||
* What was already answered without waiting, if anything. A shallow search
|
||||
* still ran, so the offer is "look further", not "look at all".
|
||||
*/
|
||||
shallowAnswerDescription: string | null;
|
||||
};
|
||||
|
||||
/** The sentence the answer view shows. */
|
||||
export function offerPrompt(offer: LongRunOffer): string {
|
||||
return (
|
||||
`${offer.reason}. This phone can keep going to ${formatInt(offer.depth)} digits — ` +
|
||||
`${describeDuration(offer.estimatedSeconds)}. Run it anyway?`
|
||||
);
|
||||
}
|
||||
|
||||
/** Two short rows for the lens. */
|
||||
export function offerGlassesPrompt(offer: LongRunOffer): string {
|
||||
return `Keep going? ${compactDuration(offer.estimatedSeconds)}\n${formatInt(offer.depth)} digits on phone`;
|
||||
}
|
||||
|
||||
/** Progress from a long local run, so a four-minute grind is not a dead screen. */
|
||||
export type LongRunProgress = {
|
||||
/** 0…1, or null when the phase cannot estimate itself. */
|
||||
fraction: number | null;
|
||||
/** What it is doing right now. */
|
||||
stage: string;
|
||||
/** Seconds elapsed so far. */
|
||||
elapsedSeconds: number;
|
||||
};
|
||||
|
||||
export function progressText(progress: LongRunProgress): string {
|
||||
if (progress.fraction === null) return progress.stage;
|
||||
return `${Math.round(progress.fraction * 100)}% ${progress.stage}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The longest run the phone will even OFFER to attempt once the wearer has
|
||||
* said they will wait. An hour reaches most five- and six-digit runs under
|
||||
* the cost model. Past it the offer is withheld rather than shown: proposing
|
||||
* a multi-hour grind that still might not answer the question is worse than
|
||||
* plainly saying this device cannot settle it.
|
||||
*/
|
||||
export const LONG_RUN_CEILING_SECONDS = 3600;
|
||||
|
||||
/**
|
||||
* Build the offer, or decline to make one. Withheld in two cases, both
|
||||
* because the wait would not buy an answer: the depth needed exceeds what
|
||||
* the phone can hold, or the run would take longer than the ceiling.
|
||||
*/
|
||||
export function longRunOffer(
|
||||
workload: MathWorkload,
|
||||
reason: string,
|
||||
shallow: string | null = null,
|
||||
): LongRunOffer | null {
|
||||
const depth = requiredDepth(workload);
|
||||
if (depth <= MAXIMUM_COMPUTED_DIGITS) return null;
|
||||
if (depth > MAXIMUM_FEASIBLE_DIGITS) return null;
|
||||
|
||||
const estimate = estimatedLocalSeconds({
|
||||
kind: "constantDigits",
|
||||
constant: workload.constant,
|
||||
count: depth,
|
||||
});
|
||||
if (estimate > LONG_RUN_CEILING_SECONDS) return null;
|
||||
|
||||
return {
|
||||
workload,
|
||||
estimatedSeconds: estimate,
|
||||
reason,
|
||||
depth,
|
||||
shallowAnswerDescription: shallow,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Accepted runs
|
||||
|
||||
/**
|
||||
* Run the search at full depth on the phone. Only called once the wearer has
|
||||
* accepted the offer's stated wait. Async and chunked — the generators yield
|
||||
* to the event loop, and the cancellation closure is checked every term.
|
||||
*/
|
||||
export async function runAcceptedSearch(
|
||||
offer: LongRunOffer,
|
||||
cancellation: ComputeCancellation = NEVER_CANCELLED,
|
||||
progress: ComputeProgress | null = null,
|
||||
): Promise<DigitSearchOutcome> {
|
||||
if (offer.workload.kind !== "digitSearch") {
|
||||
return { kind: "notFound", searchedDigits: 0 };
|
||||
}
|
||||
const expansion = await deepFractionalDigits(
|
||||
offer.workload.constant,
|
||||
offer.depth,
|
||||
cancellation,
|
||||
progress,
|
||||
);
|
||||
if (!expansion) return { kind: "notFound", searchedDigits: 0 };
|
||||
return locateDigits(offer.workload.pattern, expansion, offer.workload.occurrence);
|
||||
}
|
||||
|
||||
/** Generate the accepted depth and count overlapping occurrences there. */
|
||||
export async function runAcceptedCount(
|
||||
offer: LongRunOffer,
|
||||
cancellation: ComputeCancellation = NEVER_CANCELLED,
|
||||
progress: ComputeProgress | null = null,
|
||||
): Promise<DigitCountResult> {
|
||||
if (offer.workload.kind !== "digitCount") {
|
||||
return { occurrences: 0, searchedDigits: 0 };
|
||||
}
|
||||
const expansion = await deepFractionalDigits(
|
||||
offer.workload.constant,
|
||||
offer.depth,
|
||||
cancellation,
|
||||
progress,
|
||||
);
|
||||
if (!expansion) return { occurrences: 0, searchedDigits: 0 };
|
||||
return countInExpansion(offer.workload.pattern, expansion);
|
||||
}
|
||||
|
||||
/** Generate the digits at full depth, once the offer has been accepted. */
|
||||
export async function runAcceptedDigits(
|
||||
offer: LongRunOffer,
|
||||
cancellation: ComputeCancellation = NEVER_CANCELLED,
|
||||
progress: ComputeProgress | null = null,
|
||||
): Promise<string | null> {
|
||||
return deepFractionalDigits(offer.workload.constant, offer.depth, cancellation, progress);
|
||||
}
|
||||
Reference in new issue
Block a user