@mathzetta/inlinemath 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +326 -2
- package/dist/cas.external.js +2 -0
- package/dist/cas.js +2 -0
- package/dist/chunks/calculate-Cz87Lt0N.js +2 -0
- package/dist/chunks/draw-Bev17BJJ.js +2 -0
- package/dist/chunks/edit-C65xXzo8.js +2 -0
- package/dist/chunks/edit-M68aRA5o.js +2 -0
- package/dist/chunks/html-BimAqn7x.js +2 -0
- package/dist/chunks/html-CupluJSh.js +2 -0
- package/dist/chunks/lite-3Fb-OHbt.js +2 -0
- package/dist/fonts/GUST-FONT-LICENSE.txt +30 -0
- package/dist/fonts/fonts.css +17 -0
- package/dist/fonts/lmroman12-italic.woff2 +0 -0
- package/dist/fonts/lmroman12-regular.woff2 +0 -0
- package/dist/inlinemath-cas.external.global.min.js +2 -0
- package/dist/inlinemath-cas.global.min.js +2 -0
- package/dist/inlinemath-lite-calc.global.min.js +2 -0
- package/dist/inlinemath-lite.external.global.min.js +2 -0
- package/dist/inlinemath-lite.global.min.js +2 -0
- package/dist/inlinemath.css +158 -0
- package/dist/inlinemath.external.global.min.js +2 -0
- package/dist/inlinemath.external.js +2 -0
- package/dist/inlinemath.global.min.js +2 -0
- package/dist/inlinemath.js +2 -0
- package/dist/lite-calc.js +2 -0
- package/dist/lite.external.js +2 -0
- package/dist/lite.js +2 -0
- package/dist/markdown.external.js +2 -0
- package/dist/markdown.js +2 -0
- package/fonts/GUST-FONT-LICENSE.txt +30 -0
- package/fonts/fonts.css +17 -0
- package/fonts/lmroman12-italic.woff2 +0 -0
- package/fonts/lmroman12-regular.woff2 +0 -0
- package/inlinemath.css +158 -0
- package/package.json +95 -4
- package/src/calculator.js +6 -0
- package/src/cas.d.ts +3 -0
- package/src/cas.js +149 -0
- package/src/draw.js +72 -0
- package/src/edit.js +96 -0
- package/src/glyphs.js +40 -0
- package/src/html.js +32 -0
- package/src/index.d.ts +3 -0
- package/src/index.js +17 -0
- package/src/layout.js +649 -0
- package/src/lite-calc.d.ts +3 -0
- package/src/lite-calc.js +15 -0
- package/src/lite.d.ts +3 -0
- package/src/lite.js +18 -0
- package/src/markdown.d.ts +3 -0
- package/src/markdown.js +676 -0
- package/src/mathzetta.js +18 -0
- package/src/select.js +108 -0
- package/src/types.d.ts +204 -0
- package/src/variables.js +228 -0
- package/src/view.js +382 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* Inline Math 0.2.0 — MIT licence; MathZetta not included: map mathzetta, mathzetta/speech and mathzetta/calculate with an import map */
|
|
2
|
+
import{parse as e,operator as n}from"mathzetta";import"mathzetta/speech";import{calculateBlock as t}from"mathzetta/calculate";import{toText as r}from"mathzetta/text";import{a as o}from"./chunks/html-BimAqn7x.js";import"./chunks/draw-Bev17BJJ.js";const s=new Map,i=-1,a="\\:",u=e=>"string"==typeof e&&e.startsWith(a)&&e.length>2;function l(e){if(!e||!e.symbol)throw new Error("operator needs a symbol");if(!Number.isInteger(e.arity)||e.arity<0&&e.arity!==i)throw new Error(`operator "${e.symbol}" needs an integer arity >= 0, or VARIADIC`);if(e.commutative&&2!==e.arity)throw new Error(`only binary operators can be commutative ("${e.symbol}")`);const n={symbol:e.symbol,arity:e.arity,commutative:!!e.commutative,fold:"function"==typeof e.fold?e.fold:null,label:e.label||e.symbol};return s.set(n.symbol,n),n}const c=Object.freeze({symbol:a,arity:i,commutative:!1,fold:null,label:"function"});function f(e){const n=s.get(e);return n||(u(e)?{...c,symbol:e,label:e.slice(2)}:null)}function p(e){return s.has(e)||u(e)}const d=e=>Number.isFinite(e)&&Number.isInteger(e)?e:null,h=e=>Number.isFinite(e)?e:null;!function(){l({symbol:"+",arity:2,commutative:!0,label:"add",fold:(e,n)=>h(e+n)}),l({symbol:"-",arity:2,label:"subtract",fold:(e,n)=>h(e-n)}),l({symbol:"*",arity:2,commutative:!0,label:"multiply",fold:(e,n)=>h(e*n)}),l({symbol:"/",arity:2,label:"divide",fold:(e,n)=>0===n?null:d(e/n)}),l({symbol:"^",arity:2,label:"power",fold:(e,n)=>Number.isInteger(n)&&Math.abs(n)<=64?h(e**n):null}),l({symbol:"neg",arity:1,label:"negate",fold:e=>h(-e)}),l({symbol:"pm",arity:1,label:"plus or minus"}),l({symbol:"±",arity:2,label:"plus or minus"}),l({symbol:"mod",arity:2,label:"modulo",fold:(e,n)=>0===n?null:d((e%n+n)%n)}),l({symbol:"!",arity:1,label:"factorial",fold:e=>Number.isInteger(e)&&e>=0&&e<=18?[...Array(e).keys()].reduce((e,n)=>e*(n+1),1):null}),l({symbol:"_",arity:2,label:"subscript"}),l({symbol:"der",arity:2,label:"derivative"}),l({symbol:"int",arity:i,label:"integral"}),l({symbol:"lim",arity:i,label:"limit"}),l({symbol:"\\sumidx",arity:i,label:"sum over an index"}),l({symbol:"\\prodidx",arity:i,label:"product over an index"}),l({symbol:"abs",arity:1,label:"absolute value",fold:e=>h(Math.abs(e))}),l({symbol:"floor",arity:1,label:"floor",fold:e=>h(Math.floor(e))}),l({symbol:"ceil",arity:1,label:"ceiling",fold:e=>h(Math.ceil(e))}),l({symbol:"round",arity:2,label:"round",fold:(e,n)=>Number.isInteger(n)?h(Math.round(e*10**n)/10**n):null}),l({symbol:"fixed",arity:2,label:"fixed",fold:()=>null}),l({symbol:"sqrt",arity:1,label:"square root",fold:e=>d(Math.sqrt(e))}),l({symbol:"root",arity:2,label:"nth root",fold:(e,n)=>d(Math.round(n**(1/e))**e===n?Math.round(n**(1/e)):NaN)});for(const e of["sin","cos","tan","csc","sec","cot","sinh","cosh","tanh","arcsin","arccos","arctan","arcsinh","arccosh","arctanh","ln","loglog","logloglog","expm1"])l({symbol:e,arity:1,label:e});l({symbol:"log",arity:2,label:"log to a base"}),l({symbol:"atan2",arity:2,label:"atan2"}),l({symbol:"perm",arity:2,label:"permutations"}),l({symbol:"comb",arity:2,label:"combinations"}),l({symbol:"random",arity:0,label:"random"});for(const e of["max","min","gcd","mean","sum","prod"])l({symbol:e,arity:i,label:e});for(const e of["()","[]","{}","(]","[)"])l({symbol:e,arity:i,label:"group"});for(const e of["pmatrix","bmatrix","vmatrix"])l({symbol:e,arity:i,label:"matrix"});l({symbol:"det",arity:1,label:"determinant"});for(const e of["=","===","≠","≠=","<",">","≤","≥","∈","∉","∪","∩","≈","≡","→","pmod","&","|","\\xor","\\nand","\\nor"])l({symbol:e,arity:2,label:e});l({symbol:"\\not",arity:1,label:"not"}),l({symbol:"?:",arity:3,label:"if then else"})}();const m="num",g="sym",v="op",b=Object.freeze([]);class y extends Error{constructor(e){super(e),this.name="ExprError"}}function w(e){if("number"!=typeof e||!Number.isFinite(e))throw new y(`not a finite number: ${e}`);const n=(t=e,Object.is(t,-0)?"0":String(t));var t;return Object.freeze({type:m,token:n,value:e,args:b,s:n})}function x(e){if("string"!=typeof e||""===e)throw new y("symbol needs a non-empty token");return Object.freeze({type:g,token:e,value:null,args:b,s:e})}function q(e){const n=/^(-?)0*(\d+?)(?:\.(\d*?)0*)?$/.exec(String(e));if(!n)throw new y(`not an exact decimal: ${e}`);const[,t,r,o=""]=n,s=o?`${r}.${o}`:r,i=/^0(\.0*)?$/.test(s)?"0":t+s;return Object.freeze({type:m,token:i,value:Number(i),args:b,s:i})}const k=/^-?\d+(\.\d+)?$/;function $(e){const n=String(e);if(k.test(n))return q(n);if(""!==n&&!/\s/.test(n)){const e=Number(n);if(Number.isFinite(e))return w(e)}return x(n)}function S(e,n){const t=f(e);if(!t)throw new y(`unknown operator "${e}"`);if(t.arity!==i&&n.length!==t.arity)throw new y(`"${e}" takes ${t.arity} operand(s), got ${n.length}`);const r=Object.freeze(n.slice()),o=t.arity===i?` ${r.length}`:"",s=`${r.length?r.map(e=>e.s).join(" "):""}${r.length,""}${o} ${e}`.trimStart();return Object.freeze({type:v,op:e,token:e,value:null,args:r,s:s})}const O=e=>e.type===m,N=e=>e.type===v;function A(e){return I(function(e){const n=String(e).trim();return""===n?[]:n.split(/\s+/)}(e))}function I(e){if(!Array.isArray(e))throw new y("fromPostfix needs an array of tokens");if(0===e.length)throw new y("empty expression");const n=[];for(let t=0;t<e.length;t++){const r=String(e[t]);if(p(r)){let e=f(r).arity;if(e===i){const o=n.pop();if(e=o&&o.type===m&&Number.isInteger(o.value)&&o.value>=0?o.value:-1,e<0)throw new y(`"${r}" at position ${t+1} takes any number of operands, so a count must come before it`)}if(n.length<e)throw new y(`"${r}" at position ${t+1} needs ${e} operand(s), only ${n.length} on the stack`);const o=n.splice(n.length-e,e);n.push(S(r,o))}else n.push($(r))}if(1!==n.length){const t=[...new Set(e.filter(e=>!p(e)))];throw new y(`expression leaves ${n.length} values on the stack; it should leave exactly 1. Read as operands: ${t.join(", ")} — is one of those meant to be an operator?`)}return n[0]}function M(e){if(e.type!==v)return 0;let n=0;for(const t of e.args)n=Math.max(n,M(t));return n+1}function E(e){if(e.type!==v)return 1;let n=1;for(const t of e.args)n+=E(t);return n}function T(e,n=[]){if(e.type!==v)n.push(e.token);else for(const t of e.args)T(t,n);return n}function j(e){return e.type===m||e.type!==g&&e.args.every(j)}function Z(e,n="pre",t=[],r=[]){"pre"===n&&r.push({node:e,path:t});for(let o=0;o<e.args.length;o++)Z(e.args[o],n,t.concat(o),r);return"post"===n&&r.push({node:e,path:t}),r}function z(e,n,t){if(0===n.length)return t;const[r,...o]=n,s=e.args.slice();return s[r]=z(s[r],o,t),S(e.op,s)}class D extends Error{constructor(e){super(e),this.name="CasError"}}const B=1e5,C=e=>e<0n?-e:e,F=e=>0n===e?0:C(e).toString(2).length;function V(e,n){for(e=C(e),n=C(n);n;)[e,n]=[n,e%n];return e}class R{constructor(e,n=1n){if(0n===n)throw new D("division by zero");n<0n&&(e=-e,n=-n);const t=V(e,n)||1n;if(this.n=e/t,this.d=n/t,F(this.n)>B||F(this.d)>B)throw new D("a number too large to keep exactly")}static of(e){return new R(BigInt(e))}add(e){return new R(this.n*e.d+e.n*this.d,this.d*e.d)}sub(e){return new R(this.n*e.d-e.n*this.d,this.d*e.d)}mul(e){return new R(this.n*e.n,this.d*e.d)}div(e){if(0n===e.n)throw new D("division by zero");return new R(this.n*e.d,this.d*e.n)}neg(){return new R(-this.n,this.d)}abs(){return this.n<0n?this.neg():this}inv(){return R.ONE.div(this)}pow(e){if((e=BigInt(e))<0n)return this.inv().pow(-e);if((0n===this.n||1n===C(this.n))&&1n===this.d)return 0n===e||-1n===this.n&&e%2n==0n?R.ONE:this;if(BigInt(Math.max(F(this.n),F(this.d)))*e>BigInt(B))throw new D("a power too large to work out exactly");return new R(this.n**e,this.d**e)}get isZero(){return 0n===this.n}get isOne(){return 1n===this.n&&1n===this.d}get isInteger(){return 1n===this.d}get sign(){return this.n<0n?-1:this.n>0n?1:0}equals(e){return this.n===e.n&&this.d===e.d}compare(e){const n=this.n*e.d,t=e.n*this.d;return n<t?-1:n>t?1:0}floor(){const e=this.n/this.d;return new R(this.n<0n&&e*this.d!==this.n?e-1n:e)}ceil(){return this.neg().floor().neg()}toNumber(){const e=Number(this.n),n=Number(this.d);if(Number.isFinite(e)&&Number.isFinite(n))return e/n;const t=BigInt(Math.max(F(this.n),F(this.d))-1e3);return Number(this.n>>t)/Number(this.d>>t)}toString(){return 1n===this.d?String(this.n):`${this.n}/${this.d}`}}function U(e){const n=/^(-?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(String(e));if(!n||""===n[2]&&!n[3])return null;const[,t,r,o="",s="0"]=n;let i=new R(BigInt((r||"0")+o),10n**BigInt(o.length));const a=Number(s);return a&&(i=i.mul(R.of(10).pow(a))),t?i.neg():i}function P(e,n){if(e<2n)return e;if(n>=F(e))return 1n;const t=BigInt(n);let r=1n<<BigInt(Math.ceil(F(e)/n));for(;;){const n=((t-1n)*r+e/r**(t-1n))/t;if(n>=r)break;r=n}for(;r**t>e;)r--;for(;(r+1n)**t<=e;)r++;return r}R.ZERO=new R(0n),R.ONE=new R(1n),R.MINUS_ONE=new R(-1n),R.HALF=new R(1n,2n);const L=(()=>{const e=[],n=new Uint8Array(1e4);for(let t=2;t<n.length;t++)if(!n[t]){e.push(BigInt(t));for(let e=t*t;e<n.length;e+=t)n[e]=1}return e})();function W(e,n){const t=BigInt(n);let r=1n,o=1n,s=e;for(const e of L){if(e*e>s)break;if(s%e)continue;let n=0n;for(;s%e===0n;)s/=e,n++;r*=e**(n/t),o*=e**(n%t)}if(s>1n){const e=function(e,n){if(e<0n)return null;if(e<2n)return e;const t=P(e,n);return t**BigInt(n)===e?t:null}(s,n);null!==e?r*=e:o*=s}return{outside:r,inside:o}}const _=new Set(["pi","e","π"]),H={complex:!1};function J(e,n){const t=H.complex;H.complex=Boolean(e);try{return n()}finally{H.complex=t}}const Q=e=>_.has(e)||H.complex&&"i"===e,Y=e=>H.complex&&"atom"===e.k&&"sym"===e.node.type&&"i"===e.node.token,K=e=>({k:"num",q:e}),G=K(R.ONE),X=K(R.ZERO),ee=K(R.HALF),ne=e=>"num"===e.k,te=e=>({k:"atom",node:e}),re=new WeakMap;function oe(e){let n=re.get(e);return void 0===n&&re.set(e,n=De(e).s),n}function se(e){if("num"===e.k)return 0;if("atom"===e.k)return"sym"===e.node.type&&Q(e.node.token)?0:1;if("add"===e.k)return Math.max(...e.terms.map(e=>se(e.x)));let n=0;for(const t of e.fs){const e=se(t.b);e&&(n+=e*(ne(t.e)?t.e.q.toNumber():1))}return n}function ie(e,n){return"num"===e.k?n&&!ne(n)?3:0:Y(e)?1.5:"atom"===e.k&&"sym"===e.node.type?Q(e.node.token)?n&&!ne(n)?3:1:2:"atom"===e.k?3:4}const ae=(e,n)=>e<n?-1:e>n?1:0;function ue(e){const n=new Map,t=(e,t)=>{"atom"!==e.k||"sym"!==e.node.type||Q(e.node.token)||n.set(e.node.token,(n.get(e.node.token)??0)+t)};if("mul"===e.k)for(const n of e.fs)t(n.b,ne(n.e)?n.e.q.toNumber():1);else t(e,1);return n}function le(e,n){const t=se(n.x)-se(e.x);if(t)return t;const r=ue(e.x),o=ue(n.x);for(const e of[...new Set([...r.keys(),...o.keys()])].sort()){const n=(o.get(e)??0)-(r.get(e)??0);if(n)return n}return ae(oe(e.x),oe(n.x))}function ce(e,n){return e.isOne?n:e.isZero?X:he([K(e),n])}function fe(e){if("num"===e.k)return{coef:e.q,rest:null};if("mul"!==e.k||e.c.isOne)return{coef:R.ONE,rest:e};const n=1===e.fs.length&&ne(e.fs[0].e)&&e.fs[0].e.q.isOne?e.fs[0].b:{k:"mul",c:R.ONE,fs:e.fs};return{coef:e.c,rest:n}}function pe(e){let n=R.ZERO;const t=new Map,r=(e,n)=>{const r=oe(n),o=t.get(r);o?o.coef=o.coef.add(e):t.set(r,{coef:e,x:n})};for(const t of e)if("num"===t.k)n=n.add(t.q);else if("add"===t.k){n=n.add(t.c);for(const e of t.terms)r(e.coef,e.x)}else{const{coef:e,rest:n}=fe(t);r(e,n)}const o=[...t.values()].filter(e=>!e.coef.isZero);return o.length?n.isZero&&1===o.length?ce(o[0].coef,o[0].x):(o.sort(le),{k:"add",c:n,terms:o}):K(n)}function de(e,n){if(!ne(n))return e.isOne?{coef:R.ONE,fs:[]}:{coef:R.ONE,fs:[{b:K(e),e:n}]};const t=n.q;if(t.isInteger)return{coef:e.pow(t.n),fs:[]};if(e.isZero){if(t.sign<0)throw new D("division by zero");return{coef:R.ZERO,fs:[]}}if(e.isOne)return{coef:R.ONE,fs:[]};if(e.sign<0){if(t.d%2n==1n){const{coef:r,fs:o}=de(e.neg(),n);return{coef:t.n%2n==0n?r:r.neg(),fs:o}}if(H.complex&&2n===t.d){const{coef:r,fs:o}=de(e.neg(),n);return{coef:r,fs:[...o,{b:ve,e:K(new R(t.n))}]}}return{coef:R.ONE,fs:[{b:K(e),e:n}]}}if(!e.isInteger){const r=de(new R(e.n),n),o=de(new R(e.d),K(t.neg()));return{coef:r.coef.mul(o.coef),fs:[...r.fs,...o.fs]}}const r=t.floor(),o=t.sub(r);if(BigInt(F(e.n))*o.n>BigInt(B)||o.d>1000n)return{coef:R.ONE,fs:[{b:K(e),e:n}]};let s=r.isZero?R.ONE:e.pow(r.n);const{outside:i,inside:a}=W(e.n**o.n,Number(o.d));s=s.mul(new R(i));return{coef:s,fs:a>1n?[{b:K(new R(a)),e:K(new R(1n,o.d))}]:[]}}function he(e){let n=R.ONE;const t=new Map,r=(e,n)=>{const r=oe(e),o=t.get(r);o?o.e=pe([o.e,n]):t.set(r,{b:e,e:n})};for(const t of e)if("num"===t.k)n=n.mul(t.q);else if("mul"===t.k){n=n.mul(t.c);for(const e of t.fs)r(e.b,e.e)}else r(t,G);if(n.isZero)return X;const o=[],s=new Map;for(const e of t.values())if(!ne(e.e)||!e.e.q.isZero){if("num"===e.b.k){if(ne(e.e)&&!e.e.q.isInteger&&e.b.q.sign>0&&e.b.q.isInteger){const n=e.e.q.toString(),t=s.get(n);t?t.n*=e.b.q.n:s.set(n,{n:e.b.q.n,e:e.e});continue}const t=de(e.b.q,e.e);n=n.mul(t.coef),o.push(...t.fs);continue}if("mul"===e.b.k&&ne(e.e)&&e.e.q.isInteger){const t=me(e.b,e.e);"mul"===t.k?(n=n.mul(t.c),o.push(...t.fs)):"num"===t.k?n=n.mul(t.q):o.push({b:t,e:G});continue}o.push(e)}for(const{n:e,e:t}of s.values()){const r=de(new R(e),t);n=n.mul(r.coef),o.push(...r.fs)}if(n.isZero)return X;const i=new Map;for(const e of o){const n=oe(e.b),t=i.get(n);t?t.e=pe([t.e,e.e]):i.set(n,{...e})}let a=[...i.values()].filter(e=>!(ne(e.e)&&e.e.q.isZero));if(H.complex){a=a.flatMap(e=>{if(!Y(e.b)||!ne(e.e)||!e.e.q.isInteger)return[e];const t=(e.e.q.n%4n+4n)%4n;return t>=2n&&(n=n.neg()),t%2n?[{b:e.b,e:G}]:[]});const e=a.filter(e=>"add"===e.b.k&&ne(e.e)&&e.e.q.isInteger&&ye(e.b)),t=a.some(e=>Y(e.b)),r=e.every(e=>(e.e.q.sign<0?-e.e.q.n:e.e.q.n)<=60n);if(e.length&&r&&(e.length>1||t||!e[0].e.q.isOne)){const r=a.filter(n=>!e.includes(n)&&!Y(n.b));let o=t?[ve]:[G];for(const n of e){const e=n.e.q.sign<0?qe(n.b):n.b;for(let t=0n;t<(n.e.q.sign<0?-n.e.q.n:n.e.q.n);t++)o=we(o,Ve(e))}return he([K(n),pe(o),...r.map(e=>ge(e.b,e.e))])}}if(a.some(e=>"num"===e.b.k&&ne(e.e)&&e.e.q.compare(R.ONE)>=0))return he([K(n),...a.map(e=>"num"===e.b.k?me(e.b,e.e):{k:"mul",c:R.ONE,fs:[e]})]);if(!a.length)return K(n);if(1===a.length&&!n.isOne&&"add"===a[0].b.k&&ne(a[0].e)&&a[0].e.q.isOne){const e=a[0].b;return pe([K(n.mul(e.c)),...e.terms.map(e=>ce(n.mul(e.coef),e.x))])}return n.isOne&&1===a.length&&ne(a[0].e)&&a[0].e.q.isOne?a[0].b:(a=a.sort((e,n)=>ie(e.b,e.e)-ie(n.b,n.e)||ae(oe(e.b),oe(n.b))),{k:"mul",c:n,fs:a})}function me(e,n){if(H.complex&&ne(n)&&n.q.isInteger){if(Y(e))return he([{k:"mul",c:R.ONE,fs:[{b:e,e:n}]}]);if("add"===e.k&&ye(e)&&!n.q.isOne)return he([{k:"mul",c:R.ONE,fs:[{b:e,e:n}]}])}if(ne(n)){if(n.q.isZero){if(ne(e)&&e.q.isZero)throw new D("0^0 is undefined");return G}if(n.q.isOne)return e}if(ne(e)){const t=de(e.q,n);if(!t.fs.length)return K(t.coef);if(t.fs.some(e=>Y(e.b)))return he([K(t.coef),...t.fs.map(e=>({k:"mul",c:R.ONE,fs:[e]}))]);const r={k:"mul",c:t.coef,fs:t.fs};return t.coef.isOne&&1===t.fs.length&&ne(t.fs[0].e)&&t.fs[0].e.q.isOne?t.fs[0].b:r}if(H.complex&&ne(n)&&2n===n.q.d&&ye(e)){const t=xe(e);if(t&&ne(t.im)&&!t.im.q.isZero){const e=e=>me(e,K(R.of(2))),r=me(pe([e(t.re),e(t.im)]),ee),o=me(he([pe([r,t.re]),K(R.HALF)]),ee),s=me(he([pe([r,Se(t.re)]),K(R.HALF)]),ee);return me(pe([o,he([K(R.of(t.im.q.sign)),s,ve])]),K(new R(n.q.n)))}}if("mul"===e.k){if(ne(n)&&n.q.isInteger)return he([K(e.c.pow(n.q.n)),...e.fs.map(e=>ge(e.b,he([e.e,n])))]);if(!e.c.isOne&&e.c.sign>0)return he([me(K(e.c),n),me({k:"mul",c:R.ONE,fs:e.fs},n)]);if(e.c.isOne&&1===e.fs.length){const[t]=e.fs;if(ne(t.e)&&ne(n)&&1n===t.e.q.n&&t.e.q.d%2n==1n)return ge(t.b,he([t.e,n]))}}return{k:"mul",c:R.ONE,fs:[{b:e,e:n}]}}function ge(e,n){return ne(n)&&n.q.isZero?G:ne(e)?me(e,n):ne(n)&&n.q.isOne?e:{k:"mul",c:R.ONE,fs:[{b:e,e:n}]}}const ve=te(x("i")),be=e=>H.complex&&De(e).s.split(" ").includes("i");function ye(e){return H.complex&&be(e)&&0===Fe(De(e)).size}function we(e,n){const t=[];for(const r of e)for(const e of n)t.push(he([r,e]));return Ve(pe(t))}function xe(e){const n=[],t=[];for(const r of Ve(e)){const{coef:e,rest:o}=fe(r),s=o?Re(o):[],i=s.filter(e=>Y(e)),a=s.filter(e=>!Y(e));if(a.some(e=>be(e)))return null;(i.length?t:n).push(he([K(e),...a]))}return{re:pe(n),im:pe(t)}}function qe(e){const n=xe(e);if(!n)return me(e,K(R.MINUS_ONE));const t=pe([me(n.re,K(R.of(2))),me(n.im,K(R.of(2)))]);return he([pe([n.re,he([K(R.MINUS_ONE),n.im,ve])]),me(t,K(R.MINUS_ONE))])}const ke={re:([e])=>xe(e)?.re??null,im:([e])=>xe(e)?.im??null,conj:([e])=>{const n=xe(e);return n?pe([n.re,he([K(R.MINUS_ONE),n.im,ve])]):null},arg:([e])=>{const n=xe(e);return n?Ie("atan2",[n.im,n.re]):null},abs:([e])=>{const n=xe(e);return!n||ne(n.im)&&n.im.q.isZero?null:me(pe([me(n.re,K(R.of(2))),me(n.im,K(R.of(2)))]),ee)}},$e={Re:"re",re:"re",Im:"im",im:"im",conj:"conj",overline:"conj",bar:"conj",arg:"arg"},Se=e=>he([K(R.MINUS_ONE),e]),Oe=(e,n)=>he([e,me(n,K(R.MINUS_ONE))]),Ne=3000n,Ae={abs:([e])=>ne(e)?K(e.q.abs()):"mul"!==e.k||e.c.isOne?null:he([K(e.c.abs()),Ie("abs",[fe(e).rest])]),floor:([e])=>ne(e)?K(e.q.floor()):null,ceil:([e])=>ne(e)?K(e.q.ceil()):null,"!":([e])=>{if(!ne(e)||!e.q.isInteger||e.q.sign<0||e.q.n>Ne)return null;let n=1n;for(let t=2n;t<=e.q.n;t++)n*=t;return K(new R(n))},mod:([e,n])=>ne(e)&&ne(n)&&!n.q.isZero?K(e.q.sub(n.q.mul(e.q.div(n.q).floor()))):null,max:e=>e.every(ne)&&e.length?e.reduce((e,n)=>n.q.compare(e.q)>0?n:e):null,min:e=>e.every(ne)&&e.length?e.reduce((e,n)=>n.q.compare(e.q)<0?n:e):null,gcd:e=>e.length&&e.every(e=>ne(e)&&e.q.isInteger)?K(new R(e.reduce((e,n)=>V(e,n.q.n),0n))):null,log:([e,n])=>{if(!ne(e)||!ne(n)||e.q.sign<=0||n.q.sign<=0||e.q.isOne)return null;if(n.q.isOne)return X;const t=Math.log(n.q.toNumber())/Math.log(e.q.toNumber());if(!Number.isFinite(t))return null;for(let r=1;r<=12;r++){const o=Math.round(t*r);if(!(Math.abs(t*r-o)>1e-9||0===o)&&(Math.abs(o)<=256&&e.q.pow(BigInt(o)).equals(n.q.pow(BigInt(r)))))return K(new R(BigInt(o),BigInt(r)))}return null},comb:([e,n])=>ne(e)&&ne(n)&&e.q.isInteger&&n.q.isInteger&&e.q.sign>=0&&n.q.sign>=0&&e.q.n<=Ne?K(function(e,n){if(n>e)return R.ZERO;n>e-n&&(n=e-n);let t=1n;for(let r=1n;r<=n;r++)t=t*(e-n+r)/r;return new R(t)}(e.q.n,n.q.n)):null,perm:([e,n])=>{if(!(ne(e)&&ne(n)&&e.q.isInteger&&n.q.isInteger&&e.q.sign>=0&&n.q.sign>=0&&e.q.n<=Ne))return null;if(n.q.n>e.q.n)return X;let t=1n;for(let r=0n;r<n.q.n;r++)t*=e.q.n-r;return K(new R(t))}};function Ie(e,n){if(H.complex&&ke[e]){const t=ke[e](n);if(t)return t}const t=Ae[e];if(t){const e=t(n);if(e)return e}return te(S(e,n.map(De)))}const Me=new Map;function Ee(e){const n=H.complex?`ℂ ${e.s}`:e.s,t=Me.get(n);if(t)return t;const r=function(e){if("num"===e.type){const n=U(e.token);if(!n)throw new D(`not an exact number: ${e.token}`);return K(n)}if("sym"===e.type)return"π"===e.token?te(x("pi")):te(e);const n=e.args.map(Ee);switch(e.op){case"+":return pe(n);case"-":return((e,n)=>pe([e,Se(n)]))(n[0],n[1]);case"neg":return Se(n[0]);case"*":return he(n);case"/":return Oe(n[0],n[1]);case"^":return me(n[0],n[1]);case"sqrt":return me(n[0],ee);case"root":return me(n[1],me(n[0],K(R.MINUS_ONE)));default:{const t=e.op.startsWith("\\:")?e.op.slice(2):null;return t&&H.complex&&$e[t]&&1===n.length?Ie($e[t],n):t&&p(t)&&f(t).arity===n.length?Ie(t,n):Ie(e.op,n)}}}(e);return Me.size>2e4&&Me.clear(),Me.set(n,r),r}const Te=e=>De(Ee(e)),je=e=>q(String(e));function Ze(e){return e.isInteger?je(e.n):S("/",[je(e.n),je(e.d)])}const ze=new WeakMap;function De(e){let n=ze.get(e);return n||ze.set(e,n=function(e){switch(e.k){case"num":return Ze(e.q);case"atom":return e.node;case"mul":return function(e,n){const t=[],r=[];for(const e of n)ne(e.e)&&e.e.q.sign<0?r.push(Be(e.b,K(e.e.q.neg()))):t.push(Be(e.b,e.e));let o=1n!==e.n&&-1n!==e.n||!t.length?Ce([je(e.n),...t]):Ce(t);-1n===e.n&&t.length&&(o=S("neg",[o]));1n!==e.d&&r.unshift(je(e.d));return r.length?S("/",[o,Ce(r)]):o}(e.c,e.fs);case"add":return function(e){let n=null;const t=e=>H.complex&&be(e.x)&&0===Fe(De(e.x)).size,r=[...e.terms.filter(e=>!t(e)),...e.terms.filter(t)],o=e.c,s=()=>{o.isZero||(n=n?o.sign<0?S("-",[n,Ze(o.neg())]):S("+",[n,Ze(o)]):Ze(o))};let i=!1;for(const e of r)!i&&t(e)&&(s(),i=!0),n=n?e.coef.sign<0?S("-",[n,De(ce(e.coef.neg(),e.x))]):S("+",[n,De(ce(e.coef,e.x))]):De(ce(e.coef,e.x));i||s();return n}(e);default:throw new Error(`bad form ${e.k}`)}}(e)),n}function Be(e,n){const t=De(e);if(ne(n)){const e=n.q;if(e.isOne)return t;if(1n===e.n&&2n===e.d)return S("sqrt",[t]);if(1n===e.n)return S("root",[je(e.d),t])}return S("^",[t,De(n)])}const Ce=e=>e.reduce((e,n)=>e?S("*",[e,n]):n,null);function Fe(e,n=new Set){if("sym"===e.type)Q(e.token)||n.add(e.token);else if(N(e))for(const t of e.args)Fe(t,n);return n}function Ve(e){if("add"!==e.k)return[e];const n=e.terms.map(e=>ce(e.coef,e.x));return e.c.isZero||n.push(K(e.c)),n}function Re(e){if("num"===e.k)return[e];if("mul"!==e.k)return[e];const n=e.c.isOne?[]:[K(e.c)];for(const t of e.fs)n.push(ge(t.b,t.e));return n}const Ue="_",Pe=new WeakMap;function Le(e,n){return[...n,...f(e.op)?.arity===i?[String(e.args.length)]:[],e.op].join(" ")}function We(e,n){let t=Pe.get(e);t||Pe.set(e,t=new Map);const r=t.get(n);if(r)return r;const o=function(e,n){const t={key:Ue,slots:[e]};if(e.type!==v||n<=0)return[t];const r=e.args.map(e=>We(e,n-1)),o=[t],s=new Array(r.length).fill(0);for(;;){const n=[],t=[];for(let e=0;e<r.length;e++){const o=r[e][s[e]];n.push(o.key);for(const e of o.slots)t.push(e)}if(o.push({key:Le(e,n),slots:t}),o.length>=4096)break;let i=r.length-1;for(;i>=0&&!(++s[i]<r[i].length);i--)s[i]=0;if(i<0)break}return o}(e,n);return t.set(n,o),o}function _e(e){return e.type!==v?Ue:Le(e,e.args.map(_e))}function He(e,n=[]){if(e.type!==v)n.push(e);else for(const t of e.args)He(t,n);return n}const Je=new Map,Qe=new Map;class Ye extends Error{constructor(e){super(e),this.name="RequirementError"}}function Ke(e,n,t=""){Je.set(e,{name:e,fn:n,doc:t,arity:Math.max(0,n.length-1)})}function Ge(e,n,t=""){Qe.set(e,{name:e,fn:n,doc:t})}function Xe(e){return Je.get(e)||null}function en(e){return Qe.get(e)||null}const nn=e=>e.type===m;function tn(e,n){return e.type===v&&(e.op===n||e.args.some(e=>tn(e,n)))}Ke("always",()=>!0,"matches anything"),Ke("never",()=>!1,"matches nothing"),Ke("isLeaf",e=>e.type!==v,"a bare operand, not an operation"),Ke("isCompound",e=>e.type===v,"an operation, not a bare operand"),Ke("isSymbol",e=>e.type===g,"a non-numeric operand such as x"),Ke("isOperation",(e,n)=>e.type===v&&e.op===n,"is this specific operation"),Ke("notOperation",(e,n)=>!(e.type===v&&e.op===n),"is anything except this operation"),Ke("isNumber",nn,"a numeric literal"),Ke("isInteger",e=>nn(e)&&Number.isInteger(e.value),"a whole number"),Ke("isPositive",e=>nn(e)&&e.value>0,"greater than zero"),Ke("isNegative",e=>nn(e)&&e.value<0,"less than zero"),Ke("isNonNegative",e=>nn(e)&&e.value>=0,"zero or greater"),Ke("isZero",e=>nn(e)&&0===e.value,"exactly 0"),Ke("isOne",e=>nn(e)&&1===e.value,"exactly 1"),Ke("isNonZero",e=>nn(e)&&0!==e.value,"a number that is provably not 0"),Ke("isNotZeroLiteral",e=>!(nn(e)&&0===e.value),"anything except a literal 0"),Ke("isPositiveInteger",e=>nn(e)&&Number.isInteger(e.value)&&e.value>0,"a whole number above 0"),Ke("isNegativeInteger",e=>nn(e)&&Number.isInteger(e.value)&&e.value<0,"a whole number below 0"),Ke("isEven",e=>nn(e)&&Number.isInteger(e.value)&&e.value%2==0,"a whole even number"),Ke("isOdd",e=>nn(e)&&Number.isInteger(e.value)&&1===Math.abs(e.value%2),"a whole odd number"),Ke("greaterThan",(e,n)=>nn(e)&&e.value>Number(n),"above a given value"),Ke("lessThan",(e,n)=>nn(e)&&e.value<Number(n),"below a given value"),Ke("isValue",(e,n)=>nn(e)&&e.value===Number(n),"equals a given number"),Ke("isNumeric",j,"contains no symbols: a constant (it need not fold to a number: 1 sin)"),Ke("hasSymbol",e=>!j(e),"mentions a symbol somewhere, so it is not just a number"),Ke("isVar",(e,n)=>e.type===g&&e.token===String(n),"is exactly this symbol"),Ke("contains",(e,n)=>T(e).includes(String(n)),"mentions this operand somewhere"),Ke("isFree",(e,n)=>!T(e).includes(String(n)),"never mentions this operand"),Ke("hasOperation",(e,n)=>tn(e,String(n)),"uses this operation somewhere inside"),Ke("equals",(e,n)=>e.s===String(n),"is exactly this postfix expression");const rn=e=>e.type===v?null:e.token;function on(e){if("string"==typeof e)return{name:e,args:[]};if(Array.isArray(e)&&e.length>0&&"string"==typeof e[0])return{name:e[0],args:e.slice(1)};throw new Ye(`bad requirement: ${JSON.stringify(e)}`)}Ge("freeOf",(e,n)=>{const t=rn(n);return null!==t&&!T(e).includes(t)},"the first operand never mentions the second"),Ge("dependsOn",(e,n)=>{const t=rn(n);return null!==t&&T(e).includes(t)},"the first operand does mention the second"),Ge("sameAs",(...e)=>e.every(n=>n.s===e[0].s),"these operands are structurally identical"),Ge("differs",(...e)=>new Set(e.map(e=>e.s)).size===e.length,"these operands are all different"),Ge("sameValue",(...e)=>e.every(e=>nn(e))&&e.every(n=>n.value===e[0].value),"these operands are the same number");const sn="simplify";class an extends Error{constructor(e,n){super(n?`rule "${n}": ${e}`:e),this.name="RuleError",this.ruleId=n}}const un=/^[A-Za-z_][A-Za-z0-9_]*$/;function ln(e,n){if(O(e))return{literal:e.value};const t=e.token;if(t.startsWith("=")){const e=t.slice(1);if(""===e)throw new an('"=" needs an operand after it',n);return{token:e}}if(!un.test(t))throw new an(`"${t}" is not a usable slot name; use letters, digits and _`,n);if(p(t))throw new an(`slot name "${t}" collides with an operator`,n);return{name:t}}function cn(e){if(!N(e))return[e];const n=e.args.map(cn),t=f(e.op),r=[];for(const o of function(e){let n=[[]];for(const t of e){const e=[];for(const r of n)for(const n of t)e.push(r.concat([n]));if(n=e,n.length>64)return n.slice(0,64)}return n}(n))if(r.push(S(e.op,o)),t.commutative&&2===o.length&&o[0].s!==o[1].s&&r.push(S(e.op,[o[1],o[0]])),r.length>=64)break;return r}function fn(e,n=[]){return"op"===e.kind?e.args.forEach(e=>fn(e,n)):"const"===e.kind&&e.free&&n.push(e.node.token),n}function pn(e){if(!e||"object"!=typeof e)throw new an("rule must be a mapping");const n=e.id||e.name;if(!n)throw new an("rule needs an id");if(!e.pattern)throw new an("rule needs a pattern",n);if(void 0===e.output||null===e.output)throw new an("rule needs an output",n);let t;try{t=A(String(e.pattern))}catch(e){if(e instanceof y)throw new an(`bad pattern: ${e.message}`,n);throw e}const r=He(t).map(e=>ln(e,n)),o=new Set(r.filter(e=>e.name).map(e=>e.name)),s=function(e,n,t){const r=[],o=e.when||{};if("object"!=typeof o||Array.isArray(o))throw new an('"when" must map slot names to lists of requirements',t);for(const[e,s]of Object.entries(o)){if(!n.has(e))throw new an(`"when" mentions "${e}", which is not a slot in the pattern`,t);const o=Array.isArray(s)?s:[s];for(const n of o){const{name:o,args:s}=on(n),i=Xe(o);if(!i)throw new an(`unknown requirement "${o}"`,t);r.push({slot:e,name:o,args:s,fn:i.fn})}}return r}(e,o,n),i=function(e,n,t){const r=[],o=e.require||[];if(!Array.isArray(o))throw new an('"require" must be a list of relations',t);for(const e of o){const{name:o,args:s}=on(e),i=en(o);if(!i)throw new an(`unknown relation "${o}"`,t);if(s.length<2)throw new an(`relation "${o}" needs at least two operands`,t);for(const e of s)if("string"==typeof e&&!n.has(e)&&un.test(e))throw new an(`relation "${o}" mentions "${e}", which is not a slot in the pattern`,t);r.push({name:o,args:s,fn:i.fn})}return r}(e,o,n),a=function(e,n,t){let r;try{r=A(e)}catch(n){throw new an(`bad output "${e}": ${n.message}`,t)}const o=e=>N(e)?{kind:"op",op:e.op,args:e.args.map(o)}:O(e)?{kind:"const",node:e}:n.has(e.token)?{kind:"slot",name:e.token}:e.token.startsWith("=")?{kind:"const",node:x(e.token.slice(1))}:{kind:"const",node:e,free:!0};return o(r)}(String(e.output),o,n),u=e.commutative?cn(t):[t],l=[],c=new Set;for(const e of u){const t=_e(e),r=He(e).map(e=>ln(e,n)),o=t+"\0"+r.map(e=>e.name??(void 0!==e.literal?`#${e.literal}`:`=${e.token}`)).join(",");c.has(o)||(c.add(o),l.push({key:t,slots:r}))}const f={id:String(n),name:e.name?String(e.name):String(n),pattern:String(e.pattern),patternTree:t,output:String(e.output),outputTemplate:a,explain:e.explain?String(e.explain).trim():"",mode:e.mode?String(e.mode):sn,tags:Array.isArray(e.tags)?e.tags.map(String):[],priority:Number.isFinite(e.priority)?e.priority:0,fold:!!e.fold,commutative:!!e.commutative,enabled:void 0===e.enabled||!!e.enabled,when:s,require:i,slots:[...o],depth:M(t),bindings:l,freeSymbols:fn(a),source:e};for(const e of l)e.rule=f;return f}function dn(e){const n={};for(const t of e.when)(n[t.slot]||=[]).push(t.args.length?[t.name,...t.args]:t.name);const t={id:e.id};return e.name!==e.id&&(t.name=e.name),e.mode!==sn&&(t.mode=e.mode),t.pattern=e.pattern,Object.keys(n).length&&(t.when=n),e.require.length&&(t.require=e.require.map(e=>[e.name,...e.args])),t.output=e.output,e.explain&&(t.explain=e.explain),e.fold&&(t.fold=!0),e.commutative&&(t.commutative=!0),e.priority&&(t.priority=e.priority),e.tags.length&&(t.tags=e.tags),e.enabled||(t.enabled=!1),t}class hn extends Error{constructor(e,n){super(null==n?e:`${e} (line ${n+1})`),this.name="YamlError",this.line=n}}class mn{constructor(e){this.records=e,this.i=0,this.pushed=[]}peek(){if(this.pushed.length)return this.pushed[this.pushed.length-1];for(;this.i<this.records.length&&this.records[this.i].blank;)this.i++;return this.i<this.records.length?this.records[this.i]:null}next(){if(this.pushed.length)return this.pushed.pop();const e=this.peek();return e&&this.i++,e}push(e){this.pushed.push(e)}}const gn=e=>"-"===e||e.startsWith("- ");function vn(e){let n=null,t=0;for(let r=0;r<e.length;r++){const o=e[r];if(n)o===n?"'"===n&&"'"===e[r+1]?r++:n=null:'"'===n&&"\\"===o&&r++;else if('"'===o||"'"===o)n=o;else if("["===o||"{"===o)t++;else if("]"===o||"}"===o)t--;else if(":"===o&&0===t&&(r+1===e.length||" "===e[r+1])){const n=e.slice(0,r).trim();return""===n?null:{key:bn(n),rest:e.slice(r+1).trim()}}}return null}function bn(e){return e.length>=2&&'"'===e[0]&&'"'===e[e.length-1]?JSON.parse(e):e.length>=2&&"'"===e[0]&&"'"===e[e.length-1]?e.slice(1,-1).replace(/''/g,"'"):e}function yn(e){const n=new mn(function(e){return String(e).split(/\r?\n/).map((e,n)=>{const t=e.search(/\S/);if(-1===t)return{raw:e,n:n,indent:0,text:"",blank:!0};const r=function(e){let n=null;for(let t=0;t<e.length;t++){const r=e[t];if(n)r===n?"'"===n&&"'"===e[t+1]?t++:n=null:'"'===n&&"\\"===r&&t++;else if('"'===r||"'"===r)n=r;else if("#"===r&&(0===t||/\s/.test(e[t-1])))return e.slice(0,t)}return e}(e.slice(t)).trimEnd();return{raw:e,n:n,indent:t,text:r,blank:""===r}})}(e));let t=n.peek();if(t&&"---"===t.text&&(n.next(),t=n.peek()),!t)return null;const r=xn(n,t.indent),o=n.peek();if(o&&"..."!==o.text&&"---"!==o.text)throw new hn(`unexpected content "${o.text}"`,o.n);return r}const wn=/^[|>][-+]?\d*$/;function xn(e,n){const t=e.peek();return!t||t.indent<n?null:gn(t.text)?qn(e,t.indent):vn(t.text)?function(e,n){const t={};for(;;){const r=e.peek();if(!r||r.indent!==n)break;const o=vn(r.text);if(!o)break;e.next();const{key:s,rest:i}=o;if(""===i){const r=e.peek();r&&r.indent>n?t[s]=xn(e,r.indent):r&&r.indent===n&&gn(r.text)?t[s]=qn(e,n):t[s]=null}else wn.test(i)?t[s]=kn(e,i,n):t[s]=$n(i,r.n)}return t}(e,t.indent):(e.next(),wn.test(t.text)?kn(e,t.text,t.indent-1):$n(t.text,t.n))}function qn(e,n){const t=[];for(;;){const r=e.peek();if(!r||r.indent!==n||!gn(r.text))break;if(e.next(),"-"===r.text){const r=e.peek();t.push(r&&r.indent>n?xn(e,r.indent):null);continue}if(wn.test(r.text.slice(2).trim())){t.push(kn(e,r.text.slice(2).trim(),n));continue}const o=r.text.slice(2),s=n+2+(o.length-o.trimStart().length);e.push({raw:r.raw,n:r.n,indent:s,text:o.trim(),blank:!1}),t.push(xn(e,s))}return t}function kn(e,n,t){const r=n[0],o=(n.match(/[-+]/)||[""])[0],s=(n.match(/\d+/)||[null])[0];let i=s?t+Number(s):null;const a=[];for(;e.i<e.records.length;){const n=e.records[e.i];if(""===n.raw.trim()){a.push(""),e.i++;continue}const r=n.raw.search(/\S/);if(r<=t)break;if(null===i&&(i=r),r<i)break;a.push(n.raw.slice(i)),e.i++}for(;a.length&&""===a[a.length-1];)a.pop();let u;if("|"===r)u=a.join("\n");else{const e=[];for(const n of a)""===n?e.push("\n"):e.length&&"\n"!==e[e.length-1]?e[e.length-1]+=" "+n:e.push(n);u=e.join("").replace(/\n(?!$)/g,"\n")}return"-"===o?u:"+"===o?u+"\n":""===u?"":u+"\n"}function $n(e,n){const t=e.trim();return""===t||"~"===t||"null"===t||"Null"===t||"NULL"===t?null:"true"===t||"True"===t||"TRUE"===t||"false"!==t&&"False"!==t&&"FALSE"!==t&&("["===t[0]||"{"===t[0]?function(e,n){const t={text:e,i:0,line:n},r=On(t);if(Sn(t),t.i<t.text.length)throw new hn(`unexpected "${t.text.slice(t.i)}" in flow value`,n);return r}(t,n):'"'===t[0]||"'"===t[0]?bn(t):/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(t)?Number(t):t)}const Sn=e=>{for(;e.i<e.text.length&&/\s/.test(e.text[e.i]);)e.i++};function On(e){Sn(e);const n=e.text[e.i];return"["===n?function(e){e.i++;const n=[];for(;;){if(Sn(e),e.i>=e.text.length)throw new hn("unterminated [",e.line);if("]"===e.text[e.i])return e.i++,n;if(n.push(On(e)),Sn(e),","===e.text[e.i])e.i++;else if("]"!==e.text[e.i])throw new hn(`expected , or ] near "${e.text.slice(e.i)}"`,e.line)}}(e):"{"===n?function(e){e.i++;const n={};for(;;){if(Sn(e),e.i>=e.text.length)throw new hn("unterminated {",e.line);if("}"===e.text[e.i])return e.i++,n;const t=String(On(e));if(Sn(e),":"!==e.text[e.i])throw new hn(`expected : after "${t}"`,e.line);if(e.i++,n[t]=On(e),Sn(e),","===e.text[e.i])e.i++;else if("}"!==e.text[e.i])throw new hn(`expected , or } near "${e.text.slice(e.i)}"`,e.line)}}(e):$n(function(e){const n=e.text[e.i];if('"'===n||"'"===n){const t=e.i;for(e.i++;e.i<e.text.length;)if("\\"===e.text[e.i]&&'"'===n)e.i+=2;else if(e.text[e.i]===n){if("'"!==n||"'"!==e.text[e.i+1])return e.i++,e.text.slice(t,e.i);e.i+=2}else e.i++;throw new hn("unterminated quoted string",e.line)}const t=e.i;for(;e.i<e.text.length;){const n=e.text[e.i];if(","===n||"]"===n||"}"===n)break;if(":"===n){const n=e.text[e.i+1];if(void 0===n||/[\s,\]}]/.test(n))break}e.i++}return e.text.slice(t,e.i).trim()}(e),e.line)}const Nn=/^(true|false|null|yes|no|on|off|~)$/i;function An(e){if(null==e)return"null";if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e))throw new hn(`cannot serialise ${e}`);return String(e)}const n=String(e);return function(e){return!!(""===e||/^\s|\s$/.test(e)||/[\u0000-\u001f\u007f]/.test(e)||/^[-?:,[\]{}#&*!|>'"%@`]/.test(e)||/: |\s#/.test(e)||Nn.test(e)||/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(e))}(n)?JSON.stringify(n):n}const In=e=>null==e||"object"!=typeof e;function Mn(e){return Array.isArray(e)?`[${e.map(Mn).join(", ")}]`:e&&"object"==typeof e?`{${Object.entries(e).map(([e,n])=>`${An(e)}: ${Mn(n)}`).join(", ")}}`:An(e)}function En(e){return Array.isArray(e)?!!e.every(e=>In(e)||Array.isArray(e)&&e.every(In))&&Mn(e).length<=72:!(!e||"object"!=typeof e)&&(Object.values(e).every(e=>In(e)||Array.isArray(e)&&e.every(In))&&Mn(e).length<=72)}function Tn(e){const n=[];return jn(e,0,n),n.length?n.join("\n")+"\n":""}function jn(e,n,t){const r=" ".repeat(n);if(Array.isArray(e)){if(0===e.length)return void t.push(r+"[]");for(const r of e)Zn(r,n,t)}else{if(e&&"object"==typeof e){const o=Object.entries(e).filter(([,e])=>void 0!==e);if(0===o.length)return void t.push(r+"{}");for(const[e,r]of o)zn(e,r,n,t);return}!function(e,n,t){if("string"==typeof e&&e.includes("\n")){t.push(n+"|-");for(const r of e.replace(/\n+$/,"").split("\n"))t.push(n+" "+r);return}t.push(n+An(e))}(e,r,t)}}function Zn(e,n,t){const r=" ".repeat(n);if(null!==e&&"object"==typeof e&&!En(e)){const o=[];if(jn(e,n+2,o),0===o.length)return void t.push(r+"-");t.push(r+"- "+o[0].slice(n+2));for(let e=1;e<o.length;e++)t.push(o[e]);return}if(null===e||"object"!=typeof e)if("string"==typeof e&&e.includes("\n")){t.push(r+"- |-");for(const r of e.replace(/\n+$/,"").split("\n"))t.push(" ".repeat(n+4)+r)}else t.push(r+"- "+An(e));else t.push(r+"- "+Mn(e))}function zn(e,n,t,r){const o=" ".repeat(t),s=An(e);if("string"==typeof n&&n.includes("\n")){r.push(`${o}${s}: |-`);for(const e of n.replace(/\n+$/,"").split("\n"))r.push(" ".repeat(t+2)+e)}else{if(null!==n&&"object"==typeof n)return En(n)?void r.push(`${o}${s}: ${Mn(n)}`):(r.push(`${o}${s}:`),void jn(n,Array.isArray(n)?t:t+2,r));r.push(`${o}${s}: ${An(n)}`)}}class Dn{constructor(e=[]){this.index=new Map,this.rules=[],this.maxDepth=0,this.name="",this.views=new Map;for(const n of e)this.add(n)}add(e){const n=e&&e.bindings?e:pn(e);if(this.rules.some(e=>e.id===n.id))throw new an(`duplicate rule id "${n.id}"`);return this.rules.push(n),n.enabled&&this.link(n),n.depth>this.maxDepth&&(this.maxDepth=n.depth),this.views.clear(),n}view(e){if(!e)return this;let n=this.views.get(e);return n||(n=new Dn(this.rules.filter(n=>n.mode===e)),n.name=this.name,this.views.set(e,n)),n}modes(){return[...new Set(this.rules.map(e=>e.mode))].sort((e,n)=>e===sn?-1:n===sn?1:e.localeCompare(n))}link(e){for(const n of e.bindings){let e=this.index.get(n.key);e||this.index.set(n.key,e=[]),e.push(n),e.sort((e,n)=>n.rule.priority-e.rule.priority||n.rule.depth-e.rule.depth)}}remove(e){const n=this.rules.findIndex(n=>n.id===e);return-1!==n&&(this.rules.splice(n,1),this.reindex(),!0)}setEnabled(e,n){const t=this.get(e);return!!t&&(t.enabled=!!n,this.reindex(),!0)}reindex(){this.index=new Map,this.maxDepth=0,this.views.clear();for(const e of this.rules)e.enabled&&this.link(e),e.depth>this.maxDepth&&(this.maxDepth=e.depth)}get(e){return this.rules.find(n=>n.id===e)||null}candidates(e){return this.index.get(e)||null}get size(){return this.rules.length}static fromYaml(e,{strict:n=!0}={}){const t=yn(e);return Dn.fromSpecs(t,{strict:n})}static fromSpecs(e,{strict:n=!0}={}){let t=e,r="";if(e&&!Array.isArray(e)&&"object"==typeof e&&(t=e.rules,r=e.name?String(e.name):""),!Array.isArray(t))throw new an('expected a list of rules, or a mapping with a "rules" list');const o=new Dn;o.name=r;const s=[];for(let e=0;e<t.length;e++)try{o.add(t[e])}catch(n){s.push(`#${e+1}: ${n.message}`)}if(s.length&&n)throw new an(`${s.length} rule(s) failed to compile:\n ${s.join("\n ")}`);return o.errors=s,o}toSpecs(){return this.rules.map(dn)}toYaml(){const e=this.toSpecs();return this.name?Tn({name:this.name,rules:e}):Tn(e)}keyReport(){return[...this.index.entries()].map(([e,n])=>({key:e,rules:n.map(e=>e.rule.id)})).sort((e,n)=>e.key.localeCompare(n.key))}}function Bn(e,n){const t=Object.create(null),r=e.slots;for(let e=0;e<r.length;e++){const o=r[e],s=n[e];if(void 0!==o.literal){if(!O(s)||s.value!==o.literal)return null;continue}if(void 0!==o.token){if(s.s!==o.token)return null;continue}const i=t[o.name];if(void 0!==i){if(i.s!==s.s)return null}else t[o.name]=s}return t}function Cn(e,n){for(const t of e.when){const e=n[t.slot];if(void 0===e)return!1;if(!t.fn(e,...t.args))return!1}for(const t of e.require){const e=t.args.map(e=>void 0!==n[e]?n[e]:e);if(!t.fn(...e))return!1}return!0}function Fn(e,n){return n.rule.priority-e.rule.priority||n.rule.depth-e.rule.depth}function Vn(e,n){const t=[];if(0===n.maxDepth)return t;for(const{key:r,slots:o}of function(e,n){const t=We(e,n),r=[];for(const e of t)e.key!==Ue&&r.push(e);return r}(e,n.maxDepth)){const e=n.candidates(r);if(e)for(const n of e){const e=Bn(n,o);e&&(Cn(n.rule,e)&&t.push({rule:n.rule,binding:n,key:r,bound:e}))}}return t.sort(Fn)}function Rn(e,n){switch(e.kind){case"slot":{const t=n[e.name];if(!t)throw new Error(`output references unbound slot "${e.name}"`);return t}case"const":return e.node;case"op":return S(e.op,e.args.map(e=>Rn(e,n)));default:throw new Error(`bad output template: ${JSON.stringify(e)}`)}}const Un=4e5,Pn=()=>new D("a number too large to approximate"),Ln=e=>e<0n?-e:e;class Wn{constructor(e){this.P=e,this.S=10n**BigInt(e),this.cache=new Map}fromQ(e){return e.n*this.S/e.d}mul(e,n){return e*n/this.S}div(e,n){if(0n===n)throw new D("division by zero");return e*this.S/n}sqrt(e){if(e<0n)throw new D("the square root of a negative number is not real");return P(e*this.S,2)}series(e,n){let t=0n,r=e;for(let e=1;0n!==r;e++)if(t+=r,r=n(r,e),e>1e5)throw new D("a series did not converge");return t}atanhInv(e){const n=BigInt(e),t=n*n;let r=this.S/n,o=0n;for(let e=1n;0n!==r;e+=2n)o+=r/e,r/=t;return o}atanInv(e){const n=BigInt(e),t=n*n;let r=this.S/n,o=0n;for(let e=1n,n=1n;0n!==r;e+=2n,n=-n)o+=n*r/e,r/=t;return o}get pi(){return this.memo("pi",()=>16n*this.atanInv(5)-4n*this.atanInv(239))}get ln2(){return this.memo("ln2",()=>2n*this.atanhInv(3))}get e(){return this.memo("e",()=>this.exp(this.S))}memo(e,n){return this.cache.has(e)||this.cache.set(e,n()),this.cache.get(e)}exp(e){const n=(e+(e>=0n?this.ln2/2n:-this.ln2/2n))/this.ln2;if(n>BigInt(Un))throw Pn();if(n<-BigInt(Un))return 0n;const t=e-n*this.ln2,r=this.series(this.S,(e,n)=>e*t/this.S/BigInt(n));return n>=0n?r<<n:r>>-n}ln(e){if(e<=0n)throw new D("the log of a number that is not positive is not real");let n=0n,t=e;for(;t>=this.S;)t>>=1n,n++;for(;t<this.S/2n;)t<<=1n,n--;const r=this.div(t-this.S,t+this.S),o=this.mul(r,r);let s=r,i=0n;for(let e=1n;0n!==s;e+=2n)i+=s/e,s=this.mul(s,o);return 2n*i+n*this.ln2}sin(e){const n=2n*this.pi;let t=e%n;t>this.pi&&(t-=n),t<-this.pi&&(t+=n);const r=this.mul(t,t);return this.series(t,(e,n)=>-e*r/this.S/BigInt(2*n*(2*n+1)))}cos(e){return this.sin(e+this.pi/2n)}atan(e){if(Ln(e)>this.S){const n=this.pi/2n;return(e>0n?n:-n)-this.atan(this.div(this.S,e))}let n=e;for(let e=0;e<2;e++)n=this.div(n,this.S+this.sqrt(this.S+this.mul(n,n)));const t=this.mul(n,n);let r=n,o=0n;for(let e=1n,n=1n;0n!==r;e+=2n,n=-n)o+=n*r/e,r=this.mul(r,t);return 4n*o}asin(e){if(Ln(e)>this.S)throw new D("arcsin of a number beyond ±1 is not real");return Ln(e)===this.S?e>0n?this.pi/2n:-this.pi/2n:this.atan(this.div(e,this.sqrt(this.S-this.mul(e,e))))}}function _n(e,n,t){if(t>0n)return e.atan(e.div(n,t));if(t<0n)return e.atan(e.div(n,t))+(n>=0n?e.pi:-e.pi);if(0n===n)throw new D("the argument of 0 is undefined");return n>0n?e.pi/2n:-e.pi/2n}const Hn={add:(e,n)=>[e[0]+n[0],e[1]+n[1]],sub:(e,n)=>[e[0]-n[0],e[1]-n[1]],mul:(e,n,t)=>[e.mul(n[0],t[0])-e.mul(n[1],t[1]),e.mul(n[0],t[1])+e.mul(n[1],t[0])],div(e,n,t){const r=e.mul(t[0],t[0])+e.mul(t[1],t[1]);if(0n===r)throw new D("division by zero");return[e.div(e.mul(n[0],t[0])+e.mul(n[1],t[1]),r),e.div(e.mul(n[1],t[0])-e.mul(n[0],t[1]),r)]},abs:(e,n)=>e.sqrt(e.mul(n[0],n[0])+e.mul(n[1],n[1])),exp(e,n){const t=e.exp(n[0]);return[e.mul(t,e.cos(n[1])),e.mul(t,e.sin(n[1]))]},ln(e,n){const t=Hn.abs(e,n);if(0n===t)throw new D("the log of 0 is undefined");return[e.ln(t),_n(e,n[1],n[0])]},pow(e,n,t,r){if(0n===n[0]&&0n===n[1])return[0n,0n];if(r&&r.isInteger){let t=r.n<0n?-r.n:r.n,o=[e.S,0n],s=n;for(;t>0n;)1n&t&&(o=Hn.mul(e,o,s)),s=Hn.mul(e,s,s),t>>=1n;return r.n<0n?Hn.div(e,[e.S,0n],o):o}return Hn.exp(e,Hn.mul(e,t,Hn.ln(e,n)))},sinh:(e,n)=>(e.exp(n)-e.exp(-n))/2n,cosh:(e,n)=>(e.exp(n)+e.exp(-n))/2n},Jn={sin:(e,[n,t])=>[e.mul(e.sin(n),Hn.cosh(e,t)),e.mul(e.cos(n),Hn.sinh(e,t))],cos:(e,[n,t])=>[e.mul(e.cos(n),Hn.cosh(e,t)),-e.mul(e.sin(n),Hn.sinh(e,t))],tan:(e,n)=>Hn.div(e,Jn.sin(e,n),Jn.cos(e,n)),ln:(e,n)=>Hn.ln(e,n),sqrt:(e,n)=>Hn.exp(e,Hn.mul(e,[e.S/2n,0n],Hn.ln(e,n))),sinh:(e,[n,t])=>[e.mul(Hn.sinh(e,n),e.cos(t)),e.mul(Hn.cosh(e,n),e.sin(t))],cosh:(e,[n,t])=>[e.mul(Hn.cosh(e,n),e.cos(t)),e.mul(Hn.sinh(e,n),e.sin(t))]},Qn=e=>({q:e}),Yn=([e,n])=>0n===n?{f:e}:{z:[e,n]};function Kn(e,n,t){const r=e=>((e,n)=>n.z??[Gn(e,n),0n])(t,n[e]);switch(e.op){case"+":return Yn(Hn.add(r(0),r(1)));case"-":return Yn(Hn.sub(r(0),r(1)));case"neg":return Yn([-r(0)[0],-r(0)[1]]);case"*":return Yn(Hn.mul(t,r(0),r(1)));case"/":return Yn(Hn.div(t,r(0),r(1)));case"^":return Yn(Hn.pow(t,r(0),r(1),n[1].q));case"sqrt":return Yn(Jn.sqrt(t,r(0)));case"root":return Yn(Hn.pow(t,r(1),Hn.div(t,[t.S,0n],r(0)),n[0].q?.inv()));case"abs":return{f:Hn.abs(t,r(0))};case"arg":return{f:_n(t,r(0)[1],r(0)[0])};case"re":return{f:r(0)[0]};case"im":return{f:r(0)[1]};case"conj":return Yn([r(0)[0],-r(0)[1]]);case"log":return Yn(Hn.div(t,Hn.ln(t,r(1)),Hn.ln(t,r(0))));default:{const o=Jn[e.op];if(!o||1!==n.length)throw new D(`no complex value for ${e.op}`);return Yn(o(t,r(0)))}}}function Gn(e,n){return n.q?e.fromQ(n.q):n.f}const Xn={sin:(e,n)=>e.sin(n),cos:(e,n)=>e.cos(n),tan:(e,n)=>e.div(e.sin(n),e.cos(n)),sec:(e,n)=>e.div(e.S,e.cos(n)),csc:(e,n)=>e.div(e.S,e.sin(n)),cot:(e,n)=>e.div(e.cos(n),e.sin(n)),arcsin:(e,n)=>e.asin(n),arccos:(e,n)=>e.pi/2n-e.asin(n),arctan:(e,n)=>e.atan(n),sinh:(e,n)=>(e.exp(n)-e.exp(-n))/2n,cosh:(e,n)=>(e.exp(n)+e.exp(-n))/2n,tanh:(e,n)=>{const t=e.exp(n),r=e.exp(-n);return e.div(t-r,t+r)},arcsinh:(e,n)=>e.ln(n+e.sqrt(e.mul(n,n)+e.S)),arccosh:(e,n)=>{if(n<e.S)throw new D("arccosh of a number below 1 is not real");return e.ln(n+e.sqrt(e.mul(n,n)-e.S))},arctanh:(e,n)=>{if(Ln(n)>=e.S)throw new D("arctanh of a number beyond ±1 is not real");return e.ln(e.div(e.S+n,e.S-n))/2n},ln:(e,n)=>e.ln(n),loglog:(e,n)=>e.ln(e.ln(n)),logloglog:(e,n)=>e.ln(e.ln(e.ln(n))),expm1:(e,n)=>e.exp(n)-e.S};function et(e,n,t){if("num"===e.type)return Qn(U(e.token));if("sym"===e.type){if("pi"===e.token||"π"===e.token)return{f:n.pi};if("e"===e.token)return{f:n.e};if("i"===e.token&&H.complex)return{z:[0n,n.S]};if(t&&e.token in t){const n=t[e.token],r="number"==typeof n||"string"==typeof n||"bigint"==typeof n?U(String(n)):null;if(!r)throw new D(`the value of ${e.token} is not a number`);return Qn(r)}throw new D(`${e.token} has no value`)}H.complex&&e.op.startsWith("\\:")&&$e[e.op.slice(2)]&&(e=S($e[e.op.slice(2)],e.args));const r=e.args.map(e=>et(e,n,t));if(r.some(e=>e.z)||["re","im","conj","arg"].includes(e.op)||function(e,n){if(!H.complex)return!1;const t=e=>e.q?e.q.sign<0:void 0!==e.f&&e.f<0n;return"sqrt"===e.op||"ln"===e.op||"log"===e.op?t(n["log"===e.op?1:0])||"log"===e.op&&t(n[0]):"^"===e.op?t(n[0])&&!(n[1].q&&n[1].q.d%2n==1n):"root"===e.op&&t(n[1])&&!(n[0].q&&n[0].q.isInteger&&n[0].q.n%2n==1n)}(e,r))return Kn(e,r,n);const o=r.every(e=>e.q),s=e=>Gn(n,r[e]);switch(e.op){case"+":return o?Qn(r[0].q.add(r[1].q)):{f:s(0)+s(1)};case"-":return o?Qn(r[0].q.sub(r[1].q)):{f:s(0)-s(1)};case"neg":return r[0].q?Qn(r[0].q.neg()):{f:-r[0].f};case"*":return o?Qn(r[0].q.mul(r[1].q)):{f:n.mul(s(0),s(1))};case"/":return o?Qn(r[0].q.div(r[1].q)):{f:n.div(s(0),s(1))};case"^":return tt(n,r[0],r[1]);case"sqrt":return tt(n,r[0],Qn(R.HALF));case"root":return tt(n,r[1],r[0].q?Qn(r[0].q.inv()):{f:n.div(n.S,r[0].f)});case"abs":return r[0].q?Qn(r[0].q.abs()):{f:Ln(r[0].f)};case"floor":return Qn(r[0].q?r[0].q.floor():new R(nt(r[0].f,n.S)));case"ceil":return Qn(r[0].q?r[0].q.ceil():new R(-nt(-r[0].f,n.S)));case"log":return{f:n.div(n.ln(s(1)),n.ln(s(0)))};case"atan2":return{f:_n(n,s(0),s(1))};case"max":case"min":if(!r.length)throw new D(`${e.op} of nothing`);return o?Qn(r.map(e=>e.q).reduce((n,t)=>("max"===e.op?t.sub(n).sign>0:t.sub(n).sign<0)?t:n)):{f:r.map((e,n)=>s(n)).reduce((n,t)=>"max"===e.op?t>n?t:n:t<n?t:n)};case"sum":return o?Qn(r.reduce((e,n)=>e.add(n.q),R.ZERO)):{f:r.reduce((e,n,t)=>e+s(t),0n)};case"prod":return o?Qn(r.reduce((e,n)=>e.mul(n.q),R.ONE)):{f:r.reduce((e,t,r)=>n.mul(e,s(r)),n.S)};case"mean":if(!r.length)throw new D("mean of nothing");return o?Qn(r.reduce((e,n)=>e.add(n.q),R.ZERO).div(new R(BigInt(r.length)))):{f:r.reduce((e,n,t)=>e+s(t),0n)/BigInt(r.length)};case"mod":{if(o){if(r[1].q.isZero)throw new D("mod 0 is undefined");return Qn(r[0].q.sub(r[1].q.mul(r[0].q.div(r[1].q).floor())))}const e=s(1);if(0n===e)throw new D("mod 0 is undefined");return{f:s(0)-n.mul(e,nt(n.div(s(0),e),n.S)*n.S)}}case"round":{if(!r[1].q?.isInteger)throw new D("round needs a whole number of places");const e=10n**Ln(r[1].q.n),t=r[0].q??new R(s(0),n.S),o=r[1].q.sign>=0,i=(o?t.mul(new R(e)):t.div(new R(e))).add(R.HALF).floor();return Qn(o?i.div(new R(e)):i.mul(new R(e)))}case"!":{if(!r[0].q?.isInteger||r[0].q.sign<0)throw new D("factorial is only worked out for whole numbers");let e=1n;for(let n=2n;n<=r[0].q.n;n++)if(e*=n,0n==(255n&n)&&F(e)>Un)throw Pn();return Qn(new R(e))}default:{const t=Xn[e.op];if(!t||1!==r.length)throw new D(`no numeric value for ${e.op}`);return{f:t(n,s(0))}}}}const nt=(e,n)=>{const t=e/n;return e<0n&&t*n!==e?t-1n:t};function tt(e,n,t){if(t.q&&t.q.isInteger){if(n.q)return Qn(n.q.pow(t.q.n));let r=t.q.n;const o=r<0n;o&&(r=-r);let s=e.S,i=n.f;for(;r>0n;){if(1n&r&&(s=e.mul(s,i)),i=e.mul(i,i),F(s)>Un+4*e.P||F(i)>8e5){if(o)return{f:0n};throw Pn()}r>>=1n}return{f:o?e.div(e.S,s):s}}const r=Gn(e,n);if(0n===r){if(t.q?t.q.sign>0:t.f>0n)return Qn(R.ZERO);throw new D("0 to a power that is not positive is undefined")}if(r<0n){if(t.q&&t.q.d%2n==1n){const n=tt(e,{f:-r},t).f;return{f:t.q.n%2n==0n?n:-n}}throw new D("a negative number to a fractional power is not real")}if(t.q&&1n===Ln(t.q.n)&&t.q.d<=64n){const n=P(r*e.S**(t.q.d-1n),Number(t.q.d));return{f:t.q.n<0n?e.div(e.S,n):n}}return{f:e.exp(e.mul(Gn(e,t),e.ln(r)))}}function rt(e,n,t){const r=e<0n?"-":"",o=Ln(e);if(0n===o)return{sign:"",digits:"0",point:1};const s=o.toString(),i=s.length-n.P;let a=s.slice(0,t);s.length>t&&s[t]>="5"&&(a=(BigInt(a)+1n).toString());let u=i;return a.length>t&&(a=a.slice(0,t),u++),{sign:r,digits:a.replace(/0+$/,"")||"0",point:u}}function ot({sign:e,digits:n,point:t}){if("0"===n)return"0";if(t>21||t<-6){return`${e}${n.length>1?`${n[0]}.${n.slice(1)}`:n}e${t-1}`}return t<=0?`${e}0.${"0".repeat(-t)}${n}`:t>=n.length?`${e}${n}${"0".repeat(t-n.length)}`:`${e}${n.slice(0,t)}.${n.slice(t)}`}function st(e){let n=0n,t=0n,r=e.d;for(;r%2n==0n;)r/=2n,n++;for(;r%5n==0n;)r/=5n,t++;const o=n>t?n:t;let s=Ln(e.n)*10n**o/e.d;if(0n===s)return 1;for(;s%10n==0n;)s/=10n;return s.toString().length}function it(e){let n=e.d;for(;n%2n==0n;)n/=2n;for(;n%5n==0n;)n/=5n;return 1n===n}function at(e){const n=/^(-?[\d.]+)e(-?\d+)$/.exec(e);return n?S("*",[q(n[1]),S("^",[q("10"),q(n[2])])]):q(e)}function ut(e,{digits:n=15,scope:t}={}){if(!Number.isInteger(n)||n<1||n>1e5)throw new D("digits must be a whole number from 1 to 100000");let r=n+25,o=null;for(let s=0;s<4;s++){const i=new Wn(r),a=et(e,i,t);if(a.z){const e=ct(a.z,i,n);if(e.retry&&s<3){r+=e.retry;continue}return void 0===e.real?e:lt(e.real,i,n,null)}if(a.q&&a.q.isInteger&&Ln(a.q.n).toString().length<=n)return{text:a.q.n.toString(),node:q(a.q.n.toString()),number:Number(a.q.n),re:Number(a.q.n),im:0,exact:!0};const u=Gn(i,a);if(0n===u&&(!a.q||!a.q.isZero)&&s<3){o=null,r*=4;continue}const l=rt(u,i,n);if(o&&l.point<-10&&o.point-l.point>=(r-o.P)/2)return{text:"0",node:q("0"),number:0,re:0,im:0,exact:!1};if(!(l.point<-10&&s<3)||o&&o.point===l.point)return lt(u,i,n,a.q);o={point:l.point,P:r},r+=10-l.point}throw new D("could not approximate")}function lt(e,n,t,r){const o=ot(rt(e,n,t));return{text:o,node:at(o),number:Number(o),re:Number(o),im:0,exact:Boolean(r)&&it(r)&&st(r)<=t}}function ct([e,n],t,r){const o=10n**BigInt(Math.max(0,t.P-r-12)),s=e=>Ln(e)>o;if(!s(n))return{real:e};const i=rt(n,t,r);if(i.point<-10&&s(n))return{retry:10-i.point};const a=ot(i),u="1"===a?"i":"-1"===a?"-i":`${a}i`,l="1"===a?x("i"):S("*",[at(a.replace(/^-/,"")),x("i")]);if(!s(e))return{text:u,node:a.startsWith("-")?S("neg",[l]):l,number:NaN,re:0,im:Number(a),exact:!1};const c=ot(rt(e,t,r)),f=a.startsWith("-"),p="1"===a.replace(/^-/,"")?x("i"):S("*",[at(a.replace(/^-/,"")),x("i")]);return{text:`${c} ${f?"-":"+"} ${u.replace(/^-/,"")}`,node:S(f?"-":"+",[at(c),p]),number:NaN,re:Number(c),im:Number(a),exact:!1}}function ft(e,n={}){const t=e=>(e=>0===Fe(e).size)(e)?"num"===e.type&&/^-?\d+$/.test(e.token)?e:ut(e,n).node:N(e)?S(e.op,e.args.map(t)):e;return t(e)}const pt={variable:null},dt=(e,n)=>null!==n&&Fe(e).has(n);function ht(e){if("num"===e.type)return U(e.token);if(N(e)&&"/"===e.op&&e.args.every(e=>"num"===e.type)){const n=U(e.args[0].token),t=U(e.args[1].token);return n&&t&&!t.isZero?n.div(t):null}return null}const mt=e=>0===Fe(e).size;function gt(e,n,t){const r=function(e){const n=Ee(e);return"num"===n.k?n.q.isZero?n.q:null:"atom"===n.k&&"sym"===n.node.type&&"pi"===n.node.token?U("1"):"mul"===n.k&&1===n.fs.length&&"atom"===n.fs[0].b.k&&"pi"===n.fs[0].b.node.token&&"num"===n.fs[0].e.k&&n.fs[0].e.q.isOne?n.c:null}(e);if(!r)return!1;const[o,s="1"]=String(n).split("/");return t(r.compare(U(o).div(U(s))))}function vt(e){if(!mt(e))return NaN;try{const{number:n}=ut(e,{digits:30});return Math.sign(n)}catch{return NaN}}function bt(){Xe("hasVariable")||(Ke("hasVariable",e=>dt(e,pt.variable),"mentions the variable being solved for"),Ke("freeOfVariable",e=>null!==pt.variable&&!dt(e,pt.variable),"does not mention the variable being solved for"),Ke("isRational",e=>null!==ht(e),"an exact number: 3, -2, 1/2"),Ke("isWhole",e=>ht(e)?.isInteger??!1,"a whole number (any size)"),Ke("isEvenWhole",e=>{const n=ht(e);return Boolean(n?.isInteger&&n.n%2n==0n)},"an even whole number"),Ke("isOddWhole",e=>{const n=ht(e);return Boolean(n?.isInteger&&n.n%2n!=0n)},"an odd whole number"),Ke("isPositiveRational",e=>(ht(e)?.sign??0)>0,"an exact number above 0"),Ke("isNegativeRational",e=>(ht(e)?.sign??0)<0,"an exact number below 0"),Ke("isConstant",mt,"has no unknowns (numbers, π and e only)"),Ke("notOne",e=>{const n=ht(e);return!n||!n.isOne},"anything except the number 1"),Ke("notMinusOne",e=>{const n=ht(e);return!n||!n.equals(U("-1"))},"anything except the number -1"),Ke("hasMinusSign",e=>function(e){const n=Ee(e);return"num"===n.k?n.q.sign<0:"mul"===n.k&&n.c.sign<0}(e),"written with a leading minus: -x, -2x, -π/6"),Ke("piMultipleAtLeast",(e,n)=>gt(e,n,e=>e>=0),"a multiple of π, at least k·π"),Ke("piMultipleAbove",(e,n)=>gt(e,n,e=>e>0),"a multiple of π, above k·π"),Ke("piMultipleBelow",(e,n)=>gt(e,n,e=>e<0),"a multiple of π, below k·π"),Ke("piMultipleAtMost",(e,n)=>gt(e,n,e=>e<=0),"a multiple of π, at most k·π"),Ke("isPositiveConstant",e=>vt(e)>0,"no unknowns, and above 0 (e, π, √2, 3)"),Ke("isNegativeConstant",e=>vt(e)<0,"no unknowns, and below 0"),Ke("hasImaginaryPart",e=>{if(!H.complex)return!1;const n=xe(Ee(e));return Boolean(n)&&!("num"===n.im.k&&n.im.q.isZero)},"complex mode: has a nonzero imaginary part (unknowns count as real)"),Ke("isSymbolNode",e=>"sym"===e.type&&!_.has(e.token),"a single unknown such as x"))}function yt(e){const n=new Map;for(const t of e){const e=t.id??t.name;if(!e)throw new Error(`a rule needs an id (pattern ${t.pattern})`);n.set(String(e),{...n.get(String(e))??{},...t})}const t=[...n.values()].map(e=>{const n={...e};try{void 0!==n.pattern&&(n.pattern=function(e){const n=A(e),t=e=>"num"===e.type||("sym"===e.type?e.token.startsWith("="):e.args.every(t)),r=e=>"sym"===e.type?x(e.token.slice(1)):"num"===e.type?e:S(e.op,e.args.map(r)),o=e=>"sym"===e.type?x(`=${e.token}`):"num"===e.type?e:S(e.op,e.args.map(o)),s=e=>"op"!==e.type?e:t(e)?o(Te(r(e))):S(e.op,e.args.map(s));return s(n).s}(String(n.pattern)))}catch(e){throw new Error(`rule "${n.id}": bad pattern "${n.pattern}": ${e.message}`)}return"hidden"===n.step&&(n.tags=[...n.tags??[],"hidden"]),n});return Dn.fromSpecs(t,{strict:!0})}function wt(e,n,t,r){return e.explain?e.explain.replace(/\{(\w+)\}/g,(e,o)=>"result"===o?t?r(t):e:n[o]?r(n[o]):e).trim():""}const xt=e=>N(e)&&("+"===e.op||"-"===e.op),qt=e=>N(e)&&("*"===e.op||"/"===e.op);function*kt(e,n,{order:t="pre"}={}){for(const r of function(e,n,{order:t="post"}={}){const r=[];for(const{node:o,path:s}of Z(e,t))for(const e of Vn(o,n))r.push({...e,node:o,path:s});return r}(e,n,{order:t})){const n=Rn(r.rule.outputTemplate,r.bound);yield{rule:r.rule,bound:r.bound,path:r.path,before:r.node,after:n,next:()=>Te(z(e,r.path,n))}}for(const{node:r,path:o}of Z(e,t)){const t=xt(r);if(!t&&!qt(r))continue;const s=t?Ve(Ee(r)):Re(Ee(r));if(s.length<3)continue;const i=t?pe:he;for(let t=0;t<s.length;t++)for(let r=t+1;r<s.length;r++){const a=De(i([s[t],s[r]]));for(const u of Vn(a,n)){const n=Rn(u.rule.outputTemplate,u.bound),l=s.filter((e,n)=>n!==t&&n!==r);yield{rule:u.rule,bound:u.bound,path:o,before:a,after:n,next:()=>Te(z(e,o,De(i([Ee(n),...l]))))}}}}}function $t(e,n,{format:t,order:r="pre",maxSteps:o=200,variable:s=null}={}){const i=pt.variable;pt.variable=s;try{let s=Te(e);const i=new Set([s.s]),a=[];for(let e=0;e<o;e++){let e=null;for(const t of kt(s,n,{order:r})){const n=t.next();if(n.s!==s.s&&!i.has(n.s)){e={c:t,next:n};break}}if(!e)break;const{c:o,next:u}=e;a.push({id:o.rule.id,name:o.rule.name,tags:o.rule.tags,from:s.s,to:u.s,path:o.path,before:o.before.s,after:o.after.s,explanation:wt(o.rule,o.bound,Te(o.after),t)}),s=u,i.add(s.s)}return{node:s,steps:a}}finally{pt.variable=i}}const St={full:[],normal:["hidden"],brief:["hidden","tidy","identity","value","split","base","arithmetic"]},Ot=(e,n)=>"all"===n||"*"===n||Array.isArray(n)&&n.some(n=>n===e.id||e.tags?.includes(n));function Nt(e){if(!1===e)return null;if(void 0===e||!0===e)return{show:"all",hide:St.normal,explain:!0};if("string"==typeof e){if(!St[e])throw new Error(`steps: "${e}" is not one of ${Object.keys(St).join(", ")}`);return{show:"all",hide:St[e],explain:!0}}const n=e.detail??"normal";if(!St[n])throw new Error(`steps.detail: "${n}" is not one of ${Object.keys(St).join(", ")}`);return{show:e.show??"all",hide:[...St[n],...e.hide??[]],explain:e.explain??!0}}function At(e,n){if(!n)return[];const t=[];let r=null;for(const o of e){if(!(Ot(o,n.show)&&!Ot(o,n.hide))){r=r??{from:o.from,ids:[]},r.ids.push(o.id);continue}const e={...o};r&&(e.from=r.from,e.also=r.ids,e.path=null,r=null);!0===n.explain||!1!==n.explain&&Ot(o,n.explain)||delete e.explanation,t.push(e)}if(r&&t.length){const n=t[t.length-1];n.to=e[e.length-1].to,n.also=[...n.also??[],...r.ids]}return t}const It=K(R.ONE),Mt=(e,n)=>"atom"===e.k&&"sym"===e.node.type&&e.node.token===n;function Et(e){switch(e.k){case"num":default:return e;case"atom":return"op"===e.node.type?Ie(e.node.op,e.node.args.map(e=>Et(Ee(e)))):e;case"add":return pe(Ve(e).map(Et));case"mul":{let n=[K(e.c)];for(const t of e.fs){const e=Et(t.b);if("add"===e.k&&ne(t.e)&&t.e.q.isInteger&&t.e.q.sign>0&&t.e.q.n<=BigInt(60))for(let r=0n;r<t.e.q.n;r++)n=Tt(n,Ve(e));else n=Tt(n,[ge(e,t.e)])}return pe(n)}}}function Tt(e,n){const t=[];for(const r of e)for(const e of n)t.push(he([r,e]));return Ve(pe(t))}function jt(e,n){const t=new Map;for(const r of Ve(Et(e))){const{coef:e,rest:o}=fe(r);let s=0;const i=[K(e)];for(const e of o?Re(o):[]){const{b:t,e:r}="mul"===e.k&&1===e.fs.length&&e.c.isOne?e.fs[0]:{b:e,e:It};if(Mt(t,n)){if(!ne(r)||!r.q.isInteger||r.q.sign<0)return null;s+=Number(r.q.n)}else{if(Zt(t,n)||Zt(r,n))return null;i.push(e)}}t.set(s,pe([t.get(s)??K(R.ZERO),he(i)]))}for(const[e,n]of t)ne(n)&&n.q.isZero&&t.delete(e);return t}const Zt=(e,n)=>Fe(De(e)).has(n);function zt(e){if(!e)return null;const n=Math.max(0,...e.keys());if(n>256)return null;const t=[];for(let r=0;r<=n;r++){const n=e.get(r)??K(R.ZERO);if(!ne(n))return null;t.push(n.q)}return t}function Dt(e,n){const t=Ee(x(n));return pe(e.map((e,n)=>he([K(e),me(t,K(R.of(n)))])))}const Bt=e=>{const n=e.slice();for(;n.length>1&&n[n.length-1].isZero;)n.pop();return n},Ct=(e,n)=>e.reduceRight((e,t)=>e.mul(n).add(t),R.ZERO);function Ft(e,n){const t=e.length-1,r=new Array(t);let o=R.ZERO;for(let s=t;s>=1;s--)o=e[s].add(o.mul(n)),r[s-1]=o;return r}function Vt(e){if(0n===(e=(e=>e<0n?-e:e)(e)))return null;if(e>10n**14n)return null;const n=[];let t=e;for(let e=2n;e*e<=t;e+=2n===e?1n:2n){if(t%e)continue;let r=0;for(;t%e===0n;)t/=e,r++;n.push([e,r])}t>1n&&n.push([t,1]);let r=[1n];for(const[e,t]of n){const n=[];for(const o of r)for(let r=0,s=1n;r<=t;r++,s*=e)n.push(o*s);if(r=n,r.length>2e4)return null}return r.sort((e,n)=>e<n?-1:e>n?1:0)}function Rt(e){let n=Bt(e);const t=[];for(;n.length>1&&n[0].isZero;)t.push(R.ZERO),n=n.slice(1);if(n.length<=1)return{roots:t,rest:n};const r=n.reduce((e,n)=>e*n.d/V(e,n.d),1n),o=n.map(e=>e.n*r/e.d),s=Vt(o[0]),i=Vt(o[o.length-1]);if(!s||!i)return{roots:t,rest:n};const a=new Map;for(const e of s)for(const n of i)for(const t of[1n,-1n]){const r=new R(t*e,n);a.set(r.toString(),r)}const u=[...a.values()].sort((e,n)=>e.compare(n));for(const e of u)for(;n.length>1&&Ct(n,e).isZero;)t.push(e),n=Ft(n,e);return{roots:t.sort((e,n)=>e.compare(n)),rest:n}}function Ut(e){if("num"===e.k)return{coef:e.q,factors:[],notes:[]};if("atom"===e.k)return{coef:R.ONE,factors:[{base:e,exp:It}],notes:[]};if("mul"===e.k){let n=e.c;const t=[],r=[];for(const o of e.fs)if("add"===o.b.k&&ne(o.e)&&o.e.q.isInteger){const e=Ut(o.b);n=n.mul(e.coef.pow(o.e.q.n));for(const n of e.factors)t.push({base:n.base,exp:he([n.exp,o.e])});r.push(...e.notes)}else t.push({base:o.b,exp:o.e});return Pt(n,t,r)}return function(e){const n=Ve(e),t=[],r=n.map(e=>{const{coef:n,rest:t}=fe(e);return{coef:n,fs:t?Re(t).map(Wt):[]}}),o=r.reduce((e,n)=>({n:V(e.n,n.coef.n),d:e.d*n.coef.d/V(e.d,n.coef.d)}),{n:0n,d:1n});let s=new R(o.n||1n,o.d);Lt(e)<0&&(s=s.neg());const i=[];for(const e of r[0].fs){if(!ne(e.e)||e.e.q.sign<=0)continue;let n=e.e.q;const t=oe(e.b);let o=!0;for(const e of r.slice(1)){const r=e.fs.find(e=>oe(e.b)===t&&ne(e.e)&&e.e.q.sign>0);if(!r){o=!1;break}r.e.q.compare(n)<0&&(n=r.e.q)}o&&i.push({base:e.b,exp:K(n)})}let a=e;if(!s.isOne||i.length){const e=he([K(s),...i.map(e=>ge(e.base,e.exp))]);a=pe(n.map(n=>he([n,me(e,K(R.MINUS_ONE))]))),t.push({id:"factor.common",values:{common:e}})}const u="add"===a.k?function(e,n){const t=[..._t(e)];for(const r of t){const o=zt(jt(e,r));if(!o||o.length<3)continue;if(1!==t.length)break;const{roots:s,rest:i}=Rt(o);if(!s.length)break;const a=[];let u=i[i.length-1]??R.ONE;const l=i.map(e=>e.div(u)),c=[...s].sort((e,n)=>e.abs().compare(n.abs())||n.sign-e.sign);for(const e of c){const t=Dt([new R(-e.n),new R(e.d)],r);a.push({base:t,exp:It}),u=u.div(new R(e.d)),n.push({id:"factor.root",values:{root:K(e),factor:t}})}if(l.length>1){const e=l.reduce((e,n)=>e*n.d/V(e,n.d),1n),n=l.map(n=>n.mul(new R(e))),t=n.reduce((e,n)=>V(e,n.n),0n)||1n;u=u.mul(new R(t,e)),a.push({base:Dt(n.map(e=>e.div(new R(t))),r),exp:It})}return Pt(u,a,[])}const r=Ve(e);if(2===r.length){const[e,t]=r;for(const r of[2,3]){const o=Ht(e,r),s=Ht(Se(t),r),i=3===r?Ht(t,r):null;if(o&&s&&2===r){n.push({id:"factor.squares",values:{a:o,b:s}});const e=Ut(pe([o,Se(s)])),t=Ut(pe([o,s]));return Pt(e.coef.mul(t.coef),[...e.factors,...t.factors],[...e.notes,...t.notes])}if(3===r&&o&&(s||i)){const e=s??i,t=s?-1:1;n.push({id:t<0?"factor.cubes-difference":"factor.cubes-sum",values:{a:o,b:e}});const r=pe(t<0?[o,Se(e)]:[o,e]),a=pe([me(o,K(R.of(2))),t<0?he([o,e]):Se(he([o,e])),me(e,K(R.of(2)))]),u=Ut(r);return Pt(u.coef,[...u.factors,{base:a,exp:It}],u.notes)}}}return{coef:R.ONE,factors:[{base:e,exp:It}],notes:[]}}(a,t):Ut(a);return Pt(s.mul(u.coef),[...i,...u.factors],[...t,...u.notes.filter(e=>!t.includes(e))])}(e)}function Pt(e,n,t){const r=new Map;for(const e of n){const n=oe(e.base),t=r.get(n);t?t.exp=pe([t.exp,e.exp]):r.set(n,{...e})}return{coef:e,factors:[...r.values()].filter(e=>!(ne(e.exp)&&e.exp.q.isZero)),notes:t}}const Lt=e=>fe(Ve(e)[0]).coef.sign;const Wt=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length?{b:e.fs[0].b,e:e.fs[0].e}:{b:e,e:It},_t=e=>Fe(De(e));function Ht(e,n){const{coef:t,rest:r}=fe(e);if(t.sign<0)return null;const o=function(e,n){const t=e=>{if(e<0n)return null;let t=0n,r=1n;for(;r**BigInt(n)<=e;)r*=2n;for(;t<r-1n;){const o=(t+r)/2n;o**BigInt(n)<=e?t=o:r=o}return t**BigInt(n)===e?t:null},r=t(e.n),o=t(e.d);return null!==r&&null!==o?new R(r,o):null}(t,n);if(!o)return null;const s=[K(o)];for(const e of r?Re(r).map(Wt):[]){if(!ne(e.e))return null;const t=e.e.q.div(R.of(n));if(!t.isInteger)return null;s.push(ge(e.b,K(t)))}return he(s)}function Jt({coef:e,factors:n}){const t=[],r=[];for(const e of n){const n=ne(e.exp)&&e.exp.q.sign<0,o=n?K(e.exp.q.neg()):e.exp,s=De(ge(e.base,o));(n?r:t).push(s)}const o=e=>e.reduce((e,n)=>e?S("*",[e,n]):n,null),s=e.n<0n?-e.n:e.n;let i=t.length?o(1n===s?t:[De(K(new R(s))),...t]):De(K(new R(s)));return e.n<0n&&(i=S("neg",[i])),1n!==e.d&&r.unshift(De(K(new R(e.d)))),r.length?S("/",[i,o(r)]):i}function Qt(e){if("mul"!==e.k)return{num:e,den:It};const n=[K(new R(e.c.n))],t=[K(new R(e.c.d))];for(const r of e.fs)ne(r.e)&&r.e.q.sign<0?t.push(ge(r.b,K(r.e.q.neg()))):n.push(ge(r.b,r.e));return{num:he(n),den:he(t)}}function Yt(e){if("add"!==e.k)return Qt(e);const n=Ve(e).map(Qt),t=new Map;let r=1n;for(const e of n){const{coef:n,rest:o}=fe(e.den);r=r*n.n/V(r,n.n);for(const e of o?Re(o).map(Wt):[]){const n=oe(e.b),r=t.get(n);(!r||ne(e.e)&&ne(r.e)&&e.e.q.compare(r.e.q)>0)&&t.set(n,e)}}const o=he([K(new R(r)),...[...t.values()].map(e=>ge(e.b,e.e))]);if(ne(o)&&o.q.isOne)return{num:e,den:It};return{num:Et(pe(n.map(e=>he([e.num,o,me(e.den,K(R.MINUS_ONE))])))),den:o}}function Kt(e){const{num:n,den:t}=Yt(e);if(ne(t)&&t.q.isOne)return null;const r=Ut(n),o=Ut(t),s=new Set(r.factors.map(e=>oe(e.base))),i=o.factors.filter(e=>s.has(oe(e.base))),a=[...r.factors,...o.factors.map(e=>({base:e.base,exp:Se(e.exp)}))];return{...Pt(r.coef.div(o.coef),a,[...r.notes,...o.notes]),cancelled:i.map(e=>e.base)}}const Gt=(e,n)=>S("=",[e,n]),Xt=Te(S("+",[x("x"),S("neg",[x("x")])])),er=e=>N(e)&&"="===e.op;function nr(e,n,t,r={}){const o=[],s=(n,t,r,s,i,a={})=>o.push(e.step(n,t,r,s,i,a));s.raw=e=>o.push(e);const i=er(n)?n:Gt(n,Xt),a=Gt(Te(i.args[0]),Te(i.args[1]));a.s!==i.s&&s("normal","Work out each side",["tidy","arithmetic"],i,a);const u=[],l=[],c=new Set;u.numeric=c,ar(e,a,t,r,s,u,l,0);const f=[],p=new Set;for(const n of u.map(n=>c.has(n)?n:(n=>$t(n,e.set.view("simplify"),{format:e.format}).node)(n))){const e=n.s;if(p.has(e))continue;p.add(e);const r=c.has(n)?null:or(i,t,n);r?s("solve.reject","Check the answer",["check"],Gt(x(t),n),Gt(x(t),n),{value:n,reason:r}):f.push(n)}return f.sort(tr),{solutions:f,unsolved:l,steps:o,always:l.some(e=>e.always)}}function tr(e,n){const t=rr(e),r=rr(n);return null===t||null===r?e.s<n.s?-1:1:(Math.abs(t.im)>0)-(Math.abs(r.im)>0)||t.re-r.re||t.im-r.im}function rr(e){if(Fe(e).size)return null;try{const{re:n,im:t}=ut(e,{digits:20});return{re:n,im:t}}catch{return null}}function or(e,n,t){const[r,o]=e.args,s=new Set([...Fe(r),...Fe(o),...Fe(t)]);if(s.delete(n),s.size)return null;const i=e=>sr(e,n,t);try{const e=ut(i(r),{digits:40}),n=ut(i(o),{digits:40}),t=Math.max(1,Math.hypot(e.re,e.im),Math.hypot(n.re,n.im));return Math.hypot(e.re-n.re,e.im-n.im)>1e-12*t?"it does not make the two sides equal":null}catch(e){return`the original equation has no value there (${e.message})`}}function sr(e,n,t){return"sym"===e.type?e.token===n?t:e:N(e)?S(e.op,e.args.map(e=>sr(e,n,t))):e}const ir=24;function ar(e,n,t,r,o,s,i,a){if(a>ir)return hr(e,n,t,r,o,s,i);const u=function(e){const n=[],t=e=>{if(N(e)&&"|"===e.op)return void e.args.forEach(t);if(!er(e))return void n.push(e);const r=e.args[1],o=Z(r,"pre").find(({node:e})=>N(e)&&"pm"===e.op);if(!o)return void n.push(e);const s=o.node.args[0],i=Te(z(r,o.path,s)),a=Te(z(r,o.path,S("neg",[s])));t(Gt(e.args[0],i)),a.s!==i.s&&t(Gt(e.args[0],a))};return t(e),n}(n);if(u.length>1){o("solve.split","Two cases",["split"],n,u.reduce((e,n)=>e?S("|",[e,n]):n,null));for(const n of u)ar(e,n,t,r,o,s,i,a+1);return}if(1===u.length&&u[0].s!==n.s)return ar(e,u[0],t,r,o,s,i,a+1);const[l,c]=n.args;if("sym"===l.type&&l.token===t&&!Zt(Ee(c),t))return void s.push(c);const f=pe([Ee(l),Se(Ee(c))]);if(!Zt(f,t))return ne(f)&&f.q.isZero?(o("solve.always","Always true",["check"],n,n,{v:t}),void i.push(Object.assign(Object.create(n),{always:!0}))):void o("solve.never","No solution",["check"],n,n,{v:t});const p=Ve(f).filter(e=>Zt(e,t)),d=Ve(f).filter(e=>!Zt(e,t)),h=pe(p),m=Se(pe(d));if(H.complex){const u=jt(f,t);if(u&&[...u.values()].every(e=>!Zt(e,t))&&Math.max(...u.keys())>=2){const l=Gt(De(f),Xt);return l.s!==n.s&&o("solve.one-side","Everything on one side",["move"],n,l,{v:t}),pr(e,f,u,t,r,o,s,i,a,l)}}if(1===p.length)return ur(e,n,h,m,t,r,o,s,i,a);const g=Gt(De(f),Xt),v=jt(f,t);if(v&&[...v.values()].every(e=>!Zt(e,t))&&Math.max(...v.keys())>=2)return g.s!==n.s&&o("solve.one-side","Everything on one side",["move"],n,g,{v:t}),pr(e,f,v,t,r,o,s,i,a,g);const b=Ut(f),y=b.factors.filter(e=>Zt(e.base,t)&&!(ne(e.exp)&&e.exp.q.sign<0));if(y.length>=2||1===y.length&&b.factors.length>1){const u=Gt(Jt(b),Xt);g.s!==n.s&&o("solve.one-side","Everything on one side",["move"],n,g,{v:t}),u.s!==g.s&&o("solve.factor","Factor",["factor"],g,u,{});const l=y.map(e=>Gt(De(e.base),Xt));l.length>1&&o("solve.zero-product","A product is zero when a factor is",["split"],u,l.reduce((e,n)=>e?S("|",[e,n]):n,null),{});for(const n of l)ar(e,n,t,r,o,s,i,a+1);return}const w=Yt(f);if(Zt(w.den,t)){const u=Gt(De(w.num),Xt);return o("solve.clear-denominator","Clear the denominator",["move"],n,u,{den:De(w.den)}),ar(e,u,t,r,o,s,i,a+1)}const q=p.filter(e=>!fr(e,t));if(1===q.length&&/\b(sqrt|root|abs)\b/.test(De(q[0]).s))return ur(e,n,q[0],Se(pe(Ve(f).filter(e=>e!==q[0]))),t,r,o,s,i,a);const k=function(e,n){const t=De(e),r=new Map;for(const{node:e}of Z(t,"pre"))if(N(e)&&Fe(e).has(n))if("^"!==e.op||Fe(e.args[0]).has(n))["sin","cos","tan","ln","sqrt","abs"].includes(e.op)&&e.args[0].s===n&&r.set(e.s,e);else{const t=Ee(e.args[1]),{coef:o,rest:s}=fe(t);if(s&&o.isInteger&&De(s).s===n){const t=De(me(Ee(e.args[0]),Ee(x(n))));r.set(t.s,t)}}const o="u"===n?"w":"u";for(const e of r.values()){const r=dr(t,e,n,o);if(!r||Fe(r).has(n))continue;const s=Ee(r),i=jt(s,o);if(i&&Math.max(...i.keys())>=1)return{kernel:Ee(e),poly:s,symbol:o}}return null}(f,t);if(k){const n=k.symbol;o("solve.substitute","Substitute",["substitute"],g,Gt(De(k.poly),Xt),{u:x(n),kernel:De(k.kernel)});const u=[];ar(e,Gt(De(k.poly),Xt),n,r,o,u,i,a+1);for(const n of u)ar(e,Gt(De(k.kernel),n),t,r,o,s,i,a+1);return}return hr(e,g,t,r,o,s,i)}function ur(e,n,t,r,o,s,i,a,u,l){let c=Gt(De(t),De(r));c.s!==n.s&&i("solve.move","Move the terms",["move"],n,c,{v:o});const{coef:f,rest:p}=fe(t),d=p?Re(p):[],h=he([K(f),...d.filter(e=>!Zt(e,o))]);if(!ne(h)||!h.q.isOne){const e=he(d.filter(e=>Zt(e,o))),n=Gt(De(e),De(Oe(r,h))),t=ne(h)&&!h.q.isInteger&&(1n===h.q.n||-1n===h.q.n);i(t?"solve.multiply":"solve.divide",t?"Multiply both sides":"Divide both sides",["move"],c,n,{by:De(t?K(h.q.inv()):h),v:o}),c=n}if("sym"===c.args[0].type&&c.args[0].token===o)return void a.push(c.args[1]);const m=Ee(c.args[1]);if(ne(m)&&m.q.isZero){const n=Ee(c.args[0]),t=Re(n).filter(e=>Zt(e,o)&&!lr(e));if(t.length>1||t.length<Re(n).filter(e=>Zt(e,o)).length){const n=t.map(e=>Gt(De(cr(e)),Xt));i("solve.zero-product","A product is zero when a factor is",["split"],c,n.reduce((e,n)=>e?S("|",[e,n]):n,null),{});for(const t of n)ar(e,t,o,s,i,a,u,l+1);return}}const g=$t(c,e.set.view("isolate"),{format:e.format,maxSteps:1,variable:o});return g.steps.length?(function(e,n){for(const t of n)e.raw(t)}(i,g.steps),ar(e,g.node,o,s,i,a,u,l+1)):hr(e,c,o,s,i,a,u)}const lr=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&ne(e.fs[0].e)&&e.fs[0].e.q.sign<0,cr=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&ne(e.fs[0].e)&&e.fs[0].e.q.sign>0?e.fs[0].b:e,fr=(e,n)=>{const t=jt(e,n);return Boolean(t)&&[...t.values()].every(e=>!Zt(e,n))};function pr(e,n,t,r,o,s,i,a,u,l){const c=Math.max(...t.keys()),f=zt(t);if(H.complex&&c>=3&&c<=64&&f&&f.every((e,n)=>0===n||n===c||e.isZero)&&!f[0].isZero){const n=f[0].neg().div(f[c]),t=me(K(n.abs()),K(new R(1n,BigInt(c)))),o=[];for(let r=0;r<c;r++){const s=he([K(new R(BigInt((n.sign<0?1:0)+2*r),BigInt(c))),Ee(x("pi"))]),i=S("*",[De(t),S("+",[S("cos",[De(s)]),S("*",[x("i"),S("sin",[De(s)])])])]);o.push($t(i,e.set.view("simplify"),{format:e.format}).node)}return s("solve.roots","All n roots",["complex"],l,o.map(e=>Gt(x(r),e)).reduce((e,n)=>e?S("|",[e,n]):n),{v:r,n:String(c),last:String(c-1),r:De(K(n))}),void i.push(...o)}if(f){const{roots:t}=Rt(f);if(t.length){const t=Ut(n),c=Gt(Jt(t),Xt);if(t.factors.length>1||t.factors.some(e=>!(ne(e.exp)&&e.exp.q.isOne))){s("solve.factor","Factor",["factor"],l,c,{});const n=t.factors.filter(e=>Zt(e.base,r)).map(e=>Gt(De(e.base),Xt));n.length>1&&s("solve.zero-product","A product is zero when a factor is",["split"],c,n.reduce((e,n)=>e?S("|",[e,n]):n,null),{});for(const t of n)ar(e,t,r,o,s,i,a,u+1);return}}}if(2===c){const e=t.get(2),n=t.get(1)??K(R.ZERO),o=t.get(0)??K(R.ZERO),a=pe([me(n,K(R.of(2))),he([K(R.of(-4)),e,o])]);if(ne(a)&&a.q.sign<0&&!H.complex)return void s("solve.no-real","No real solutions",["quadratic"],l,l,{D:De(a)});const u=he([K(R.of(2)),e]),c=me(a,K(R.HALF)),f=De(Oe(pe([Se(n),c]),u)),p=De(Oe(pe([Se(n),Se(c)]),u)),d=f.s===p.s?Gt(x(r),f):S("|",[Gt(x(r),f),Gt(x(r),p)]);return s(H.complex&&ne(a)&&a.q.sign<0?"solve.quadratic-complex":"solve.quadratic","The quadratic formula",["quadratic"],l,d,{a:De(e),b:De(n),c:De(o),D:De(a),root:De(c),v:r}),i.push(f),void(p.s!==f.s&&i.push(p))}return hr(e,l,r,o,s,i,a)}function dr(e,n,t,r){if(e.s===n.s)return x(r);if(!N(e))return e;if("^"===e.op&&"^"===n.op&&e.args[0].s===n.args[0].s){const n=Ee(e.args[1]),{coef:o,rest:s}=fe(n);if(s&&De(s).s===t&&o.isInteger)return S("^",[x(r),De(K(o))])}return S(e.op,e.args.map(e=>dr(e,n,t,r)))}function hr(e,n,t,r,o,s,i){if(r.approximate){const e="number"==typeof r.approximate?r.approximate:15,i=Ee(S("-",[n.args[0],n.args[1]])),a=H.complex?zt(jt(i,t)):null,u=a&&a.length>2?function(e,n){const t=e.length-1,r=e[t],o=e.map(e=>e/r),s=(e,n)=>{let r=1,s=0;for(let i=t-1;i>=0;i--)[r,s]=[r*e-s*n+o[i],r*n+s*e];return[r,s]};let i=Array.from({length:t},(e,n)=>[1.3*Math.cos(2*Math.PI*n/t+.4),1.3*Math.sin(2*Math.PI*n/t+.4)]);for(let e=0;e<500;e++){let e=0;if(i=i.map(([n,r],o)=>{let[a,u]=s(n,r);for(let e=0;e<t;e++){if(e===o)continue;const t=n-i[e][0],s=r-i[e][1],l=t*t+s*s;[a,u]=[(a*t+u*s)/l,(u*t-a*s)/l]}return e=Math.max(e,Math.hypot(a,u)),[n-a,r-u]}),e<1e-15)break}const a=e=>Math.abs(e)<1e-12?0:Number(e.toPrecision(n));return i.map(([e,n])=>[a(e),a(n)]).sort((e,n)=>(0!==e[1])-(0!==n[1])||e[0]-n[0]||e[1]-n[1]).map(([e,n])=>{const t=mr(e);if(0===n)return t;const r=S("*",[mr(Math.abs(n)),x("i")]);return 0===e?n<0?S("neg",[r]):r:S(n<0?"-":"+",[t,r])})}(a.map(e=>e.toNumber()),Math.min(e,14)):function(e,n,t){const r=Ee(S("-",[e.args[0],e.args[1]])),o=De(r),s=e=>{try{return ut(sr(o,n,gr(e)),{digits:30}).number}catch{return NaN}},i=[],a=[];for(let e=-400;e<=400;e++)a.push(Math.sign(e)*(Math.abs(e)/20)**2);for(let e=0;e+1<a.length;e++){let n=a[e],r=a[e+1],o=s(n);const u=s(r);if(Number.isNaN(o)||Number.isNaN(u))continue;if(0===o){i.push(gr(n));continue}if(o*u>0)continue;for(let e=0;e<200&&r-n>1e-16*Math.abs(n);e++){const e=(n+r)/2,t=s(e);if(Number.isNaN(t))break;o*t<=0?r=e:(n=e,o=t)}const l=(n+r)/2;Math.abs(s(l))<1e-6&&i.push(gr(Number(l.toPrecision(Math.min(t,15)))))}return i}(n,t,e);for(const e of u)s.numeric?.add(e);return o("solve.numeric","Numeric solutions",["numeric"],n,u.length?u.map(e=>Gt(x(t),e)).reduce((e,n)=>e?S("|",[e,n]):n):n,{v:t,count:String(u.length)}),void s.push(...u)}o("solve.unsolved","No exact method",["unsolved"],n,n,{v:t}),i.push(n)}const mr=e=>q(String(e).includes("e")?e.toFixed(20):String(e)),gr=e=>q(Number.isInteger(e)?String(e):e.toFixed(17));const vr=(e,n)=>S("int",[e,"string"==typeof n?x(n):n]);function br(e,n,t,r=0){if(r>6)throw new D("integration went too deep");const o=[],s=e.set.view("integrate"),i=$t(n,e.set.view("simplify"),{format:e.format});o.push(...i.steps);let a=Te(vr(i.node,t));for(let n=0;n<40;n++){const n=$t(a,s,{format:e.format});o.push(...n.steps),a=n.node;const t=Z(a,"pre").find(({node:e})=>{return N(n=e)&&"int"===n.op&&2===n.args.length;var n});if(!t)return{node:a,steps:o};const i=yr(e,t.node,r);if(!i)throw new D(`no rule for ∫ ${e.format(t.node.args[0])} d${t.node.args[1].token}`);o.push(...i.steps),a=Te(z(a,t.path,i.node))}throw new D("integration did not finish")}function yr(e,n,t){const[r,o]=n.args,s=o.token,i=Ee(r),a=function(e,n){const{num:t,den:r}=Yt(e),o=Ut(t),s=Ut(r),i=o.coef.div(s.coef);if(i.isOne||!Zt(e,n))return null;const a=he([...o.factors.map(e=>ge(e.base,e.exp)),...s.factors.map(e=>ge(e.base,Se(e.exp)))]);return{c:i,rest:a}}(i,s);if(a){const t=S("*",[De(K(a.c)),vr(De(a.rest),o)]);return{node:t,steps:[e.step("integrate.constant","Take the number out",["split"],n,t,{c:De(K(a.c))})]}}const u=Et(i);if(De(u).s!==r.s&&"add"===u.k){const t=vr(De(u),o);return{node:t,steps:[e.step("integrate.expand","Multiply out",["expand"],n,t,{})]}}const l=function(e,n){const t=new Map;for(const{node:r}of Z(e,"pre")){if(!N(r))continue;const e="^"===r.op?r.args:"/"===r.op?[r.args[1]]:"der"===r.op||"int"===r.op?[]:1===r.args.length||"root"===r.op?[r.args[r.args.length-1]]:[];for(const r of e){if("sym"===r.type||!Fe(r).has(n))continue;const e=jt(Ee(r),n);if(!e||1!==Math.max(...e.keys()))continue;const o=e.get(1);Zt(o,n)||ne(o)&&o.q.isZero||t.set(r.s,{node:r,a:o})}}for(const r of t.values()){if(!Fe(wr(e,r.node,x("§"))).has(n))return r}return null}(r,s);if(l){const o="u"===s?"t":"u",i=wr(r,l.node,x(o));if(!Fe(i).has(s)){const r=br(e,Te(i),o,t+1),a=Te(sr(r.node,o,l.node)),u=De(Oe(Ee(a),l.a));return{node:u,steps:[e.step("integrate.substitute","Substitute",["substitute"],n,Te(vr(i,o)),{u:x(o),inside:l.node,a:De(l.a),v:s}),...r.steps,e.step("integrate.back","Substitute back",["substitute"],r.node,u,{u:x(o),inside:l.node})]}}}const c=function(e,n,t,r){const{num:o,den:s}=Yt(t);if(!Zt(s,r))return null;const i=zt(jt(o,r)),a=zt(jt(s,r));if(!i||!a||a.length<2)return null;const u=Ee(x(r)),l=e=>Dt(e,r);if(i.length>=a.length){const{q:t,r:o}=function(e,n){const t=Bt(n);let r=Bt(e);const o=t[t.length-1];if(o.isZero)throw new D("division by the zero polynomial");const s=new Array(Math.max(1,r.length-t.length+1)).fill(R.ZERO);for(;r.length>=t.length&&(1!==r.length||!r[0].isZero);){const e=r.length-t.length,n=r[r.length-1].div(o);if(s[e]=n,r=Bt(r.map((r,o)=>o>=e&&o-e<t.length?r.sub(n.mul(t[o-e])):r)),r.length-1<e+t.length-1&&r[r.length-1].isZero)break;if(r.length<t.length)break}return{q:Bt(s),r:r}}(i,a),s=vr(De(pe([l(t),Oe(l(o),l(a))])),x(r));return{node:s,steps:[e.step("integrate.divide","Divide the polynomials",["divide"],n,s,{})]}}const{roots:c,rest:f}=Rt(a),p=new Set(c.map(String)).size===c.length;if(!c.length||!p||1!==f.length)return null;const d=(e=>e.length<=1?[R.ZERO]:e.slice(1).map((e,n)=>e.mul(R.of(n+1))))(a),h=c.map(e=>Oe(K(Ct(i,e).div(Ct(d,e))),pe([u,K(e.neg())]))),m=vr(De(pe(h)),x(r));return{node:m,steps:[e.step("integrate.partial-fractions","Partial fractions",["partial-fractions"],n,m,{})]}}(e,n,i,s);return c||function(e,n,t,r,o){if(o>=6)return null;const s=Re(t),i=s.filter(e=>xr(e,r)||!Zt(e,r)),a=s.filter(e=>!i.includes(e));if(1!==a.length)return null;const u=he(i),l=a[0];if(!Zt(u,r))return null;const c=De(l),f=N(c)?c.op:"";let p,d,h;"ln"===f||"arctan"===f||"arcsin"===f?(p=l,d=u):(p=u,d=l);try{h=br(e,De(d),r,o+1)}catch{return null}const m=Ee(e.differentiate(De(p),r)),g=he([p,Ee(h.node)]),v=vr(De(he([m,Ee(h.node)])),x(r)),b=Te(S("-",[De(g),v]));return{node:b,steps:[e.step("integrate.parts","Integration by parts",["parts"],n,b,{u:De(p),dv:De(d),V:h.node,du:De(m),v:r})]}}(e,n,i,s,t)}function wr(e,n,t){return e.s===n.s?t:N(e)?S(e.op,e.args.map(e=>wr(e,n,t))):e}const xr=(e,n)=>{const t=jt(e,n);return Boolean(t)&&[...t.values()].every(e=>!Zt(e,n))&&Math.max(...t.keys())>=1};function qr(e,n,t,r,o,s){for(const e of[r,o])if(Fe(e).has("∞")||/∞|infinity/.test(e.s))throw new D("integrals to infinity need limits, which this CAS does not do yet");if(s&&!Fe(r).size&&!Fe(o).size){const i=ut(r,{digits:20}).number,a=ut(o,{digits:20}).number,u=[...Fe(s)].filter(e=>e!==t);if(!u.length){const[r,o]=i<=a?[i,a]:[a,i];for(const i of function(e,n){const t=[],r={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};return Z(e,"pre").forEach(({node:e})=>{if(!N(e))return;let o=null;"/"===e.op?o=e.args[1]:"^"===e.op&&"num"===e.args[1].type&&e.args[1].value<0||"^"===e.op&&N(e.args[1])&&"neg"===e.args[1].op?o=e.args[0]:r[e.op]&&(o=S(r[e.op],[e.args[0]])),o&&Fe(o).has(n)&&!t.some(e=>e.s===o.s)&&t.push(o)}),t}(s,t)){let s=[];try{s=e.solve(S("=",[i,q("0")]),t,{steps:!1}).solutions}catch{continue}for(const i of s){const s=ut(i,{digits:20});if(!Number.isFinite(s.number)||s.im||s.number<r||s.number>o)continue;if(s.number>r&&s.number<o)throw new D(`the integrand has no value at ${t} = ${e.format(i)}, between the limits, so F(b) - F(a) would be wrong`);let a=NaN;try{a=ut(Te(sr(n,t,i)),{digits:15}).number}catch{}if(!Number.isFinite(a))throw new D(`the integral diverges at ${t} = ${e.format(i)}: F has no value at that limit`)}}}for(let e=0;!u.length&&e<=64;e++){const n=i+(a-i)*(e+.5)/65;try{const e=ut(sr(s,t,q(n.toFixed(15))),{digits:15}).number;if(!Number.isFinite(e))throw new D("not finite")}catch(e){throw new D(`the integrand has no value at ${t} = ${n.toPrecision(6)}, between the limits, so F(b) - F(a) would be wrong`)}}}const i=e=>Te(sr(n,t,e)),a=Te(S("-",[i(o),i(r)])),u=S("-",[i(o),i(r)]);return{value:a,step:e.step("integrate.evaluate","Between the limits",["evaluate"],n,u,{a:r,b:o,F:n,v:t})}}const kr={"=":1,"≠":1,"<":1,">":1,"≤":1,"≥":1,"+":2,"-":2,"±":2,"*":3,"/":3,neg:4,pm:4,"^":5},$r={pi:"π","≤":"≤","≥":"≥"};function Sr(e){return Mr(e).text}function Or(e,n,t=!1){return e.prec<n||t&&e.prec===n?`(${e.text})`:e.text}const Nr=e=>"op"===e.type?e.op:null,Ar=e=>e.text.startsWith("-"),Ir={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function Mr(e){if("num"===e.type)return{text:e.token,prec:e.token.startsWith("-")?4:9};if("sym"===e.type)return{text:$r[e.token]??e.token,prec:9};const n=e.args.map(Mr),t=kr[e.op];switch(e.op){case"+":case"-":case"±":{const r="+"===e.op&&["+","-"].includes(Nr(e.args[1])),o=Ar(n[1])?`(${n[1].text})`:r?n[1].text:Or(n[1],t,!0);return{text:`${Or(n[0],t)} ${"±"===e.op?"±":e.op} ${o}`,prec:t}}case"*":{const r=Or(n[0],t),o=Ar(n[1])?`(${n[1].text})`:"*"===Nr(e.args[1])?n[1].text:Or(n[1],t,!0);return{text:"num"===e.args[0].type&&"num"!==e.args[1].type&&!/^[\d(-]/.test(o)||"sym"===e.args[1].type&&"i"===e.args[1].token&&!/[\dA-Za-z]$/.test(r)?`${r}${o}`:`${r}·${o}`,prec:t}}case"/":return{text:`${Or(n[0],t)}/${Or(n[1],t,!0)}`,prec:t};case"^":return{text:`${Or(n[0],t+1)}^${Or(n[1],t)}`,prec:t};case"neg":return{text:`-${Or(n[0],3)}`,prec:4};case"pm":return{text:`±${Or(n[0],4)}`,prec:4};case"!":return{text:`${Or(n[0],9)}!`,prec:6};case"abs":return{text:`|${n[0].text}|`,prec:9};case"root":return{text:`root(${n[0].text}, ${n[1].text})`,prec:9};case"der":return{text:`d/d${n[1].text} (${n[0].text})`,prec:6};case"int":return{text:4===n.length?`∫ from ${n[2].text} to ${n[3].text} of ${n[0].text} d${n[1].text}`:`∫ ${n[0].text} d${n[1].text}`,prec:1};case"|":return{text:`${n[0].text} or ${n[1].text}`,prec:0};case"_":return{text:`${Or(n[0],9)}_${n[1].prec>=9&&!/\s/.test(n[1].text)?n[1].text:`(${n[1].text})`}`,prec:9};case"()":case"[]":case"{}":case"(]":case"[)":return{text:`${Ir[e.op][0]}${n.map(e=>e.text).join(", ")}${Ir[e.op][1]}`,prec:9};case"&":return{text:`${n[0].text} and ${n[1].text}`,prec:0};default:return void 0!==t?{text:`${Or(n[0],t)} ${e.op} ${Or(n[1],t,!0)}`,prec:t}:{text:`${e.op.replace(/^\\:?/,"")}(${n.map(e=>e.text).join(", ")})`,prec:9}}}const Er=['name: Differentiation\n\n# `u v der` means d(u)/dv (MathZetta\'s postfix: mathzetta/docs/postfix.md). Every rule here rewrites one derivative into smaller\n# derivatives, so differentiating always terminates: the expressions sitting\n# under a `D` get strictly smaller at every step.\n#\n# The variable is a slot, not a fixed letter, so these rules work for d/dx,\n# d/dt or anything else. That is what freeOf and dependsOn are for: they ask\n# whether one operand mentions whatever the variable slot bound to.\n#\n# Where two rules share a structure key, requirements keep them apart and\n# priority picks the one that reads better. The constant-multiple rule outranks\n# the product rule for exactly that reason.\n\nrules:\n # ---- the two base cases ----------------------------------------------\n - id: d-constant\n name: Derivative of a constant\n mode: differentiate\n pattern: c v der\n require:\n - [freeOf, c, v]\n output: "0"\n priority: 10\n explain: "{c} does not change when {v} changes, so its rate of change is 0."\n tags: [base]\n\n - id: d-variable\n name: Derivative of the variable\n mode: differentiate\n pattern: u v der\n require:\n - [sameAs, u, v]\n output: "1"\n priority: 10\n explain: "{v} changes exactly as fast as itself, so the rate is 1."\n tags: [base]\n\n # ---- splitting a derivative into smaller ones ------------------------\n - id: d-sum\n name: Sum rule\n mode: differentiate\n pattern: u w + v der\n output: u v der w v der +\n explain: "Differentiate {u} and {w} separately, then add the two results."\n tags: [split]\n\n - id: d-difference\n name: Difference rule\n mode: differentiate\n pattern: u w - v der\n output: u v der w v der -\n explain: "Differentiate {u} and {w} separately, then subtract the second from the first."\n tags: [split]\n\n - id: d-negate\n name: Derivative of a negative\n mode: differentiate\n pattern: u neg v der\n output: u v der neg\n explain: "The minus sign just carries through to the derivative of {u}."\n tags: [split]\n\n - id: d-constant-multiple\n name: Constant multiple rule\n mode: differentiate\n pattern: c u * v der\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v der *\n priority: 5\n explain: "{c} is only a scale factor, so it comes along unchanged while {u} is differentiated."\n tags: [split]\n\n - id: d-constant-divisor\n name: Dividing by a constant\n mode: differentiate\n pattern: u c / v der\n require:\n - [freeOf, c, v]\n output: u v der c /\n priority: 5\n explain: "Dividing by {c} is only a scale factor, so differentiate {u} and keep the division."\n tags: [split]\n\n - id: d-product\n name: Product rule\n mode: differentiate\n pattern: u w * v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u v der w * u w v der * +\n explain: "Differentiate {u} and keep {w}, then keep {u} and differentiate {w}, and add the two."\n tags: [split]\n\n - id: d-quotient\n name: Quotient rule\n mode: differentiate\n pattern: u w / v der\n output: u v der w * u w v der * - w 2 ^ /\n explain: "Bottom times the derivative of the top, minus top times the derivative of the bottom, all over {w} squared."\n tags: [split]\n\n # ---- powers -----------------------------------------------------------\n - id: d-power-of-variable\n name: Power rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: n u n 1 - ^ *\n fold: true\n priority: 6\n explain: "Bring the {n} down in front and drop the power by one."\n tags: [power]\n\n - id: d-power-chain\n name: Power rule with the chain rule\n mode: differentiate\n pattern: u n ^ v der\n require:\n - [freeOf, n, v]\n - [dependsOn, u, v]\n output: n u n 1 - ^ * u v der *\n fold: true\n explain: "Bring the {n} down and drop the power by one, then multiply by the derivative of {u}."\n tags: [power, chain]\n\n - id: d-exponential-base\n name: Derivative of a constant to a power\n mode: differentiate\n pattern: a u ^ v der\n require:\n - [freeOf, a, v]\n - [dependsOn, u, v]\n output: a u ^ a ln * u v der *\n explain: "A constant base gives itself back, multiplied by the natural log of {a} and the derivative of {u}."\n tags: [power, chain]\n\n # ---- the standard functions, each with its chain-rule factor ---------\n # e^u is `=e u ^`: the base is the literal symbol e. Outranks the general\n # a^u rule (which would give e^u · ln e · u\').\n - id: d-exp\n name: Derivative of e to a power\n mode: differentiate\n pattern: =e u ^ v der\n require:\n - [dependsOn, u, v]\n output: =e u ^ u v der *\n priority: 7\n explain: "e to a power is its own derivative, times the derivative of {u}."\n tags: [chain]\n\n - id: d-ln\n name: Derivative of a natural log\n mode: differentiate\n pattern: u ln v der\n output: u v der u /\n explain: "The derivative of {u} over {u} itself."\n tags: [chain]\n\n - id: d-sqrt\n name: Derivative of a square root\n mode: differentiate\n pattern: u sqrt v der\n output: u v der 2 u sqrt * /\n explain: "The derivative of {u}, over twice the square root of {u}."\n tags: [chain]\n\n - id: d-sin\n name: Derivative of sine\n mode: differentiate\n pattern: u sin v der\n output: u cos u v der *\n explain: "Sine differentiates to cosine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cos\n name: Derivative of cosine\n mode: differentiate\n pattern: u cos v der\n output: u sin u v der * neg\n explain: "Cosine differentiates to minus sine, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-tan\n name: Derivative of tangent\n mode: differentiate\n pattern: u tan v der\n output: u v der u cos 2 ^ /\n explain: "The derivative of {u}, over cosine squared of {u}."\n tags: [chain, trig]\n\n # ---- the rest of the standard functions -----------------------------\n - id: d-csc\n name: Derivative of cosecant\n mode: differentiate\n pattern: u csc v der\n output: u csc u cot * u v der * neg\n explain: "Cosecant differentiates to minus cosecant times cotangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-sec\n name: Derivative of secant\n mode: differentiate\n pattern: u sec v der\n output: u sec u tan * u v der *\n explain: "Secant differentiates to secant times tangent, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-cot\n name: Derivative of cotangent\n mode: differentiate\n pattern: u cot v der\n output: u v der u sin 2 ^ / neg\n explain: "Minus the derivative of {u}, over sine squared of {u}."\n tags: [chain, trig]\n\n - id: d-arcsin\n name: Derivative of arcsine\n mode: differentiate\n pattern: u arcsin v der\n output: u v der 1 u 2 ^ - sqrt /\n explain: "The derivative of {u}, over the square root of 1 minus {u} squared."\n tags: [chain, trig]\n\n - id: d-arccos\n name: Derivative of arccosine\n mode: differentiate\n pattern: u arccos v der\n output: u v der 1 u 2 ^ - sqrt / neg\n explain: "Minus the derivative of {u}, over the square root of 1 minus {u} squared."\n tags: [chain, trig]\n\n - id: d-arctan\n name: Derivative of arctangent\n mode: differentiate\n pattern: u arctan v der\n output: u v der 1 u 2 ^ + /\n explain: "The derivative of {u}, over 1 plus {u} squared."\n tags: [chain, trig]\n\n - id: d-sinh\n name: Derivative of hyperbolic sine\n mode: differentiate\n pattern: u sinh v der\n output: u cosh u v der *\n explain: "Hyperbolic sine differentiates to hyperbolic cosine, times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-cosh\n name: Derivative of hyperbolic cosine\n mode: differentiate\n pattern: u cosh v der\n output: u sinh u v der *\n explain: "Hyperbolic cosine differentiates to hyperbolic sine — no minus sign, unlike cosine — times the derivative of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-tanh\n name: Derivative of hyperbolic tangent\n mode: differentiate\n pattern: u tanh v der\n output: u v der u cosh 2 ^ /\n explain: "The derivative of {u}, over hyperbolic cosine squared of {u}."\n tags: [chain, hyperbolic]\n\n - id: d-arcsinh\n name: Derivative of inverse hyperbolic sine\n mode: differentiate\n pattern: u arcsinh v der\n output: u v der u 2 ^ 1 + sqrt /\n explain: "The derivative of {u}, over the square root of {u} squared plus 1."\n tags: [chain, hyperbolic]\n\n - id: d-arccosh\n name: Derivative of inverse hyperbolic cosine\n mode: differentiate\n pattern: u arccosh v der\n output: u v der u 2 ^ 1 - sqrt /\n explain: "The derivative of {u}, over the square root of {u} squared minus 1."\n tags: [chain, hyperbolic]\n\n - id: d-arctanh\n name: Derivative of inverse hyperbolic tangent\n mode: differentiate\n pattern: u arctanh v der\n output: u v der 1 u 2 ^ - /\n explain: "The derivative of {u}, over 1 minus {u} squared."\n tags: [chain, hyperbolic]\n\n # log base a: `a u log` in MathZetta\'s postfix\n - id: d-log\n name: Derivative of a logarithm\n mode: differentiate\n pattern: a u log v der\n require:\n - [freeOf, a, v]\n output: u v der u a ln * /\n explain: "The derivative of {u}, over {u} times the natural log of {a}."\n tags: [chain]\n\n - id: d-abs\n name: Derivative of an absolute value\n mode: differentiate\n pattern: u abs v der\n output: u u abs / u v der *\n explain: "The absolute value keeps the sign of {u}: {u} over its absolute value, times the derivative of {u}."\n tags: [chain]\n\n # n-th root: `n u root`\n - id: d-root\n name: Derivative of a root\n mode: differentiate\n pattern: n u root v der\n require:\n - [freeOf, n, v]\n output: u v der n n u root n 1 - ^ * /\n fold: true\n explain: "The derivative of {u}, over {n} times the {n}th root of {u} to the power {n} minus 1."\n tags: [chain]\n','name: More derivatives\n\n# Derivative rules the CAS adds to rules/calculus.yaml (which calcvidnew also uses).\n\nrules:\n - id: d-general-power\n name: A power with the variable in both places\n mode: differentiate\n pattern: u w ^ v der\n require:\n - [dependsOn, u, v]\n - [dependsOn, w, v]\n output: u w ^ w v der u ln * w u v der * u / + *\n explain: "Write {u}^{w} as e^({w} ln {u}) and use the chain rule: the derivative is {u}^{w} times the derivative of {w} ln {u}."\n tags: [chain]\n','name: Integrals\n\n# mode: integrate. `f v 2 int` is ∫ f dv (MathZetta\'s postfix; the 2 counts f and v).\n# Each rule turns one integral into smaller ones, or into an answer. The CAS also\n# tries, when no rule fits: multiplying out, a linear substitution (∫ f(ax + b) dx\n# from the rule for ∫ f(u) du), and integration by parts for polynomial × e^, sin,\n# cos, ln, arctan. Definite integrals are the antiderivative between the limits.\n#\n# Patterns see the normal form: 1/x is "1 x /", x^-2 is "1 x 2 ^ /", √x is "x sqrt",\n# 1/√(1 - x²) is "1 x 2 ^ neg 1 + sqrt /".\n\nrules:\n # ---- splitting -----------------------------------------------------------\n - id: i-sum\n name: Sum rule\n mode: integrate\n pattern: u w + v 2 int\n output: u v 2 int w v 2 int +\n explain: "Integrate {u} and {w} separately, and add."\n tags: [split]\n\n - id: i-difference\n name: Difference rule\n mode: integrate\n pattern: u w - v 2 int\n output: u v 2 int w v 2 int -\n explain: "Integrate {u} and {w} separately, and subtract."\n tags: [split]\n\n - id: i-negate\n name: A minus sign\n mode: integrate\n pattern: u neg v 2 int\n output: u v 2 int neg\n explain: "The minus sign comes out of the integral."\n tags: [split]\n\n - id: i-constant-multiple\n name: Constant multiple\n mode: integrate\n pattern: c u * v 2 int\n commutative: true\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: c u v 2 int *\n priority: 5\n explain: "{c} doesn\'t change with {v}, so it comes out of the integral."\n tags: [split]\n\n - id: i-constant-divisor\n name: Dividing by a constant\n mode: integrate\n pattern: u c / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n output: u v 2 int c /\n priority: 5\n explain: "Dividing by {c} comes out of the integral."\n tags: [split]\n\n - id: i-constant-over\n name: A constant over something\n mode: integrate\n pattern: c u / v 2 int\n require:\n - [freeOf, c, v]\n - [dependsOn, u, v]\n when:\n c: [notOne]\n output: c 1 u / v 2 int *\n priority: 4\n explain: "{c} comes out of the integral, leaving ∫ 1/{u}."\n tags: [split]\n\n # ---- the table -----------------------------------------------------------\n - id: i-constant\n name: Integral of a constant\n mode: integrate\n pattern: c v 2 int\n require:\n - [freeOf, c, v]\n output: c v *\n priority: 10\n explain: "A constant {c} integrates to {c}·{v}."\n tags: [base]\n\n - id: i-variable\n name: Integral of the variable\n mode: integrate\n pattern: u v 2 int\n require:\n - [sameAs, u, v]\n output: v 2 ^ 2 /\n priority: 10\n explain: "∫ {v} d{v} = {v}²/2."\n tags: [base]\n\n - id: i-power\n name: Power rule\n mode: integrate\n pattern: u n ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notMinusOne]\n output: v n 1 + ^ n 1 + /\n explain: "Add 1 to the power and divide by the new power: {result}."\n tags: [power]\n\n - id: i-reciprocal\n name: Integral of 1/x\n mode: integrate\n pattern: 1 u / v 2 int\n require:\n - [sameAs, u, v]\n output: v abs ln\n explain: "∫ 1/{v} d{v} = ln|{v}| (the power rule can\'t divide by 0 here)."\n tags: [log]\n\n - id: i-reciprocal-power\n name: Power rule (a power below)\n mode: integrate\n pattern: 1 u n ^ / v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n when:\n n: [notOne]\n output: v 1 n - ^ 1 n - /\n explain: "1/{v}^{n} is {v}^(-{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-sqrt\n name: Integral of a square root\n mode: integrate\n pattern: u sqrt v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v 3 2 / ^ * 3 /\n explain: "√{v} is {v}^(1/2): add 1 to the power and divide by 3/2."\n tags: [power]\n\n - id: i-reciprocal-sqrt\n name: Integral of 1/√x\n mode: integrate\n pattern: 1 u sqrt / v 2 int\n require:\n - [sameAs, u, v]\n output: 2 v sqrt *\n explain: "1/√{v} is {v}^(-1/2): add 1 to the power and divide by 1/2."\n tags: [power]\n\n - id: i-root\n name: Integral of a root\n mode: integrate\n pattern: n u root v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, n, v]\n output: v 1 n / 1 + ^ 1 n / 1 + /\n explain: "The {n}th root of {v} is {v}^(1/{n}): add 1 to the power and divide by it."\n tags: [power]\n\n - id: i-exp\n name: Integral of e^x\n mode: integrate\n pattern: =e u ^ v 2 int\n require:\n - [sameAs, u, v]\n output: =e v ^\n explain: "e^{v} is its own integral."\n tags: [exp]\n\n - id: i-exponential\n name: Integral of a^x\n mode: integrate\n pattern: a u ^ v 2 int\n require:\n - [sameAs, u, v]\n - [freeOf, a, v]\n output: a v ^ a ln /\n explain: "∫ {a}^{v} d{v} = {a}^{v} / ln {a}."\n tags: [exp]\n\n - id: i-ln\n name: Integral of ln x\n mode: integrate\n pattern: u ln v 2 int\n require:\n - [sameAs, u, v]\n output: v v ln * v -\n explain: "By parts: ∫ ln {v} d{v} = {v} ln {v} - {v}."\n tags: [log]\n\n - { id: i-sin, name: Integral of sin, mode: integrate, pattern: u sin v 2 int, require: [[sameAs, u, v]], output: v cos neg, tags: [trig], explain: "The derivative of -cos {v} is sin {v}." }\n - { id: i-cos, name: Integral of cos, mode: integrate, pattern: u cos v 2 int, require: [[sameAs, u, v]], output: v sin, tags: [trig], explain: "The derivative of sin {v} is cos {v}." }\n - { id: i-tan, name: Integral of tan, mode: integrate, pattern: u tan v 2 int, require: [[sameAs, u, v]], output: v cos abs ln neg, tags: [trig], explain: "tan = sin/cos, and -ln|cos {v}| differentiates to it." }\n - { id: i-sec-squared, name: Integral of sec², mode: integrate, pattern: 1 u cos 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is 1/cos²{v}." }\n - { id: i-sec-squared-written, name: Integral of sec², mode: integrate, pattern: u sec 2 ^ v 2 int, require: [[sameAs, u, v]], output: v tan, tags: [trig], explain: "The derivative of tan {v} is sec²{v}." }\n - { id: i-csc-squared, name: Integral of csc², mode: integrate, pattern: 1 u sin 2 ^ / v 2 int, require: [[sameAs, u, v]], output: v cot neg, tags: [trig], explain: "The derivative of -cot {v} is 1/sin²{v}." }\n - { id: i-sin-squared, name: Integral of sin², mode: integrate, pattern: u sin 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / -, tags: [trig], explain: "sin²{v} = (1 - cos 2{v})/2, which integrates term by term." }\n - { id: i-cos-squared, name: Integral of cos², mode: integrate, pattern: u cos 2 ^ v 2 int, require: [[sameAs, u, v]], output: v 2 / 2 v * sin 4 / +, tags: [trig], explain: "cos²{v} = (1 + cos 2{v})/2, which integrates term by term." }\n - { id: i-sinh, name: Integral of sinh, mode: integrate, pattern: u sinh v 2 int, require: [[sameAs, u, v]], output: v cosh, tags: [trig], explain: "The derivative of cosh {v} is sinh {v}." }\n - { id: i-cosh, name: Integral of cosh, mode: integrate, pattern: u cosh v 2 int, require: [[sameAs, u, v]], output: v sinh, tags: [trig], explain: "The derivative of sinh {v} is cosh {v}." }\n - { id: i-arctan, name: Integral of 1/(1 + x²), mode: integrate, pattern: 1 u 2 ^ 1 + / v 2 int, require: [[sameAs, u, v]], output: v arctan, tags: [trig], explain: "The derivative of arctan {v} is 1/(1 + {v}²)." }\n - { id: i-arcsin, name: Integral of 1/√(1 - x²), mode: integrate, pattern: 1 u 2 ^ neg 1 + sqrt / v 2 int, require: [[sameAs, u, v]], output: v arcsin, tags: [trig], explain: "The derivative of arcsin {v} is 1/√(1 - {v}²)." }\n','name: Values and identities\n\n# The CAS\'s simplify rules (mode: simplify). They see expressions in normal form\n# (src/cas/form.js), as drawn: x/2, 2x - 3, -x, √x is "x sqrt",\n# ∛x is "3 x root", π/6 is "=pi 6 /", 2π/3 is "2 =pi * 3 /", e^x is "=e x ^".\n#\n# - a word is a slot (u, v, n …); a fixed symbol is written =pi, =e\n# - a number is itself; "1 2 /" is ½\n# - arithmetic (2 + 3, x + x, √8 = 2√2) is done for you before and after every rule\n# - a rule for a sum or product of two parts also fires on any two parts of a longer one\n# - tags pick what a step list shows (steps: \'brief\' hides value, identity, tidy …)\n#\n# To change one: copy it into a file of your own with the same id and edit it;\n# to turn one off: give its id with enabled: false. createCAS({ rules: [yours] }).\n\nrules:\n # ---- logs and exponentials -------------------------------------------\n - id: ln-one\n name: Log of 1\n pattern: 1 ln\n output: "0"\n explain: "e^0 = 1, so ln 1 = 0."\n tags: [value]\n\n - id: ln-e\n name: Log of e\n pattern: =e ln\n output: "1"\n explain: "e^1 = e, so ln e = 1."\n tags: [value]\n\n - id: ln-exp\n name: Log undoes e to a power\n pattern: =e u ^ ln\n output: u\n explain: "ln and e^ undo each other: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: exp-ln\n name: e to a power undoes the log\n pattern: =e u ln ^\n output: u\n explain: "e^ and ln undo each other: e^(ln {u}) = {u} (for {u} > 0)."\n tags: [inverse]\n\n - id: exp-multiple-ln\n name: A multiple of a log in a power\n pattern: =e n u ln * ^\n when:\n n: [isRational]\n output: u n ^\n explain: "e^({n} ln {u}) = (e^(ln {u}))^{n} = {result}."\n tags: [inverse]\n\n - id: log-same-base\n name: Log of its own base\n pattern: b b log\n output: "1"\n explain: "{b}^1 = {b}, so the log of {b} to base {b} is 1."\n tags: [value]\n\n - id: log-of-power\n name: Log undoes a power of its base\n pattern: b b u ^ log\n output: u\n explain: "log base {b} and {b}^ undo each other."\n tags: [inverse]\n\n - id: power-of-log\n name: A power undoes the log to its base\n pattern: b b u log ^\n output: u\n explain: "{b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n # ---- roots and absolute value --------------------------------------------\n - id: sqrt-of-square\n name: Square root of a square\n pattern: u 2 ^ sqrt\n output: u abs\n explain: "√({u}²) is the size of {u}, whatever its sign: |{u}|."\n tags: [identity]\n\n - id: abs-squared\n name: Absolute value squared\n pattern: u abs 2 ^\n output: u 2 ^\n explain: "Squaring removes the sign anyway: |{u}|² = {u}²."\n tags: [identity]\n\n - id: abs-of-abs\n name: Absolute value twice\n pattern: u abs abs\n output: u abs\n explain: "|{u}| is never negative, so its absolute value is itself."\n tags: [identity]\n\n - id: abs-positive\n name: Absolute value of a positive number\n pattern: u abs\n when:\n u: [isPositiveConstant]\n output: u\n explain: "{u} is positive, so |{u}| = {u}."\n tags: [value]\n\n - id: abs-negative\n name: Absolute value of a negative number\n pattern: u abs\n when:\n u: [isNegativeConstant]\n output: u neg\n explain: "{u} is negative, so |{u}| = -({u})."\n tags: [value]\n\n - id: abs-of-exp\n name: e to a power is positive\n pattern: =e u ^ abs\n output: =e u ^\n explain: "e to any power is positive, so the absolute value changes nothing."\n tags: [identity]\n\n # ---- trigonometry: signs and turns ---------------------------------------\n - id: sin-odd\n name: Sine of a negative angle\n pattern: u sin\n when:\n u: [hasMinusSign]\n output: u neg sin neg\n explain: "sin(-θ) = -sin θ."\n tags: [symmetry]\n\n - id: cos-even\n name: Cosine of a negative angle\n pattern: u cos\n when:\n u: [hasMinusSign]\n output: u neg cos\n explain: "cos(-θ) = cos θ."\n tags: [symmetry]\n\n - id: tan-odd\n name: Tangent of a negative angle\n pattern: u tan\n when:\n u: [hasMinusSign]\n output: u neg tan neg\n explain: "tan(-θ) = -tan θ."\n tags: [symmetry]\n\n - id: sin-full-turn\n name: A full turn\n pattern: u sin\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - sin\n explain: "Turning a full 2π brings you back: sin({u}) = sin({u} - 2π)."\n tags: [symmetry]\n\n - id: cos-full-turn\n name: A full turn\n pattern: u cos\n when:\n u: [[piMultipleAtLeast, 2]]\n output: u 2 =pi * - cos\n explain: "Turning a full 2π brings you back: cos({u}) = cos({u} - 2π)."\n tags: [symmetry]\n\n - id: tan-half-turn\n name: Tangent repeats every π\n pattern: u tan\n when:\n u: [[piMultipleAtLeast, 1]]\n output: u =pi - tan\n explain: "tan repeats every π: tan({u}) = tan({u} - π)."\n tags: [symmetry]\n\n - id: sin-half-turn\n name: A half turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - sin neg\n explain: "Half a turn flips the sign: sin({u}) = -sin({u} - π)."\n tags: [symmetry]\n\n - id: cos-half-turn\n name: A half turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1], [piMultipleBelow, 2]]\n output: u =pi - cos neg\n explain: "Half a turn flips the sign: cos({u}) = -cos({u} - π)."\n tags: [symmetry]\n\n - id: sin-second-quarter\n name: The second quarter turn\n pattern: u sin\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - sin\n explain: "sin({u}) = sin(π - {u})."\n tags: [symmetry]\n\n - id: cos-second-quarter\n name: The second quarter turn\n pattern: u cos\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleAtMost, 1]]\n output: =pi u - cos neg\n explain: "cos({u}) = -cos(π - {u})."\n tags: [symmetry]\n\n - id: tan-second-quarter\n name: The second quarter turn\n pattern: u tan\n when:\n u: [[piMultipleAbove, 1/2], [piMultipleBelow, 1]]\n output: =pi u - tan neg\n explain: "tan({u}) = -tan(π - {u})."\n tags: [symmetry]\n\n # ---- trigonometry: the standard angles -------------------------------------\n - { id: sin-0, name: Sine of 0, pattern: 0 sin, output: "0", tags: [value], explain: "sin 0 = 0." }\n - { id: sin-pi-6, name: Sine of π/6, pattern: =pi 6 / sin, output: 1 2 /, tags: [value], explain: "sin(π/6) = 1/2." }\n - { id: sin-pi-4, name: Sine of π/4, pattern: =pi 4 / sin, output: 2 sqrt 2 /, tags: [value], explain: "sin(π/4) = √2/2." }\n - { id: sin-pi-3, name: Sine of π/3, pattern: =pi 3 / sin, output: 3 sqrt 2 /, tags: [value], explain: "sin(π/3) = √3/2." }\n - { id: sin-pi-2, name: Sine of π/2, pattern: =pi 2 / sin, output: "1", tags: [value], explain: "sin(π/2) = 1." }\n - { id: sin-pi, name: Sine of π, pattern: =pi sin, output: "0", tags: [value], explain: "sin π = 0." }\n - { id: cos-0, name: Cosine of 0, pattern: 0 cos, output: "1", tags: [value], explain: "cos 0 = 1." }\n - { id: cos-pi-6, name: Cosine of π/6, pattern: =pi 6 / cos, output: 3 sqrt 2 /, tags: [value], explain: "cos(π/6) = √3/2." }\n - { id: cos-pi-4, name: Cosine of π/4, pattern: =pi 4 / cos, output: 2 sqrt 2 /, tags: [value], explain: "cos(π/4) = √2/2." }\n - { id: cos-pi-3, name: Cosine of π/3, pattern: =pi 3 / cos, output: 1 2 /, tags: [value], explain: "cos(π/3) = 1/2." }\n - { id: cos-pi-2, name: Cosine of π/2, pattern: =pi 2 / cos, output: "0", tags: [value], explain: "cos(π/2) = 0." }\n - { id: cos-pi, name: Cosine of π, pattern: =pi cos, output: "-1", tags: [value], explain: "cos π = -1." }\n - { id: tan-0, name: Tangent of 0, pattern: 0 tan, output: "0", tags: [value], explain: "tan 0 = 0." }\n - { id: tan-pi-6, name: Tangent of π/6, pattern: =pi 6 / tan, output: 3 sqrt 3 /, tags: [value], explain: "tan(π/6) = √3/3." }\n - { id: tan-pi-4, name: Tangent of π/4, pattern: =pi 4 / tan, output: "1", tags: [value], explain: "tan(π/4) = 1." }\n - { id: tan-pi-3, name: Tangent of π/3, pattern: =pi 3 / tan, output: 3 sqrt, tags: [value], explain: "tan(π/3) = √3." }\n - { id: arcsin-0, name: Arcsine of 0, pattern: 0 arcsin, output: "0", tags: [value], explain: "sin 0 = 0, so arcsin 0 = 0." }\n - { id: arcsin-half, name: Arcsine of 1/2, pattern: 1 2 / arcsin, output: =pi 6 /, tags: [value], explain: "sin(π/6) = 1/2, so arcsin(1/2) = π/6." }\n - { id: arcsin-1, name: Arcsine of 1, pattern: 1 arcsin, output: =pi 2 /, tags: [value], explain: "sin(π/2) = 1, so arcsin 1 = π/2." }\n - { id: arccos-0, name: Arccosine of 0, pattern: 0 arccos, output: =pi 2 /, tags: [value], explain: "cos(π/2) = 0, so arccos 0 = π/2." }\n - { id: arccos-half, name: Arccosine of 1/2, pattern: 1 2 / arccos, output: =pi 3 /, tags: [value], explain: "cos(π/3) = 1/2, so arccos(1/2) = π/3." }\n - { id: arccos-1, name: Arccosine of 1, pattern: 1 arccos, output: "0", tags: [value], explain: "cos 0 = 1, so arccos 1 = 0." }\n - { id: arccos-minus-1, name: Arccosine of -1, pattern: -1 arccos, output: =pi, tags: [value], explain: "cos π = -1, so arccos(-1) = π." }\n - { id: arctan-0, name: Arctangent of 0, pattern: 0 arctan, output: "0", tags: [value], explain: "tan 0 = 0, so arctan 0 = 0." }\n - { id: arctan-1, name: Arctangent of 1, pattern: 1 arctan, output: =pi 4 /, tags: [value], explain: "tan(π/4) = 1, so arctan 1 = π/4." }\n - { id: sinh-0, name: sinh of 0, pattern: 0 sinh, output: "0", tags: [value], explain: "sinh 0 = 0." }\n - { id: cosh-0, name: cosh of 0, pattern: 0 cosh, output: "1", tags: [value], explain: "cosh 0 = 1." }\n - { id: tanh-0, name: tanh of 0, pattern: 0 tanh, output: "0", tags: [value], explain: "tanh 0 = 0." }\n\n - { id: arctan-sqrt3, name: Arctangent of √3, pattern: 3 sqrt arctan, output: =pi 3 /, tags: [value], explain: "tan(π/3) = √3, so arctan √3 = π/3." }\n - { id: arctan-sqrt3-over-3, name: Arctangent of √3/3, pattern: 3 sqrt 3 / arctan, output: =pi 6 /, tags: [value], explain: "tan(π/6) = √3/3, so arctan(√3/3) = π/6." }\n\n # atan2(y, x): the angle of the point (x, y), in (-π, π]\n - id: atan2-right\n name: The angle of a point to the right\n pattern: y x atan2\n when:\n x: [isPositiveConstant]\n output: y x / arctan\n explain: "For x > 0, atan2(y, x) = arctan(y/x)."\n tags: [value]\n - id: atan2-left-up\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isPositiveConstant]\n output: y x / arctan =pi +\n explain: "For x < 0 and y > 0, atan2(y, x) = arctan(y/x) + π."\n tags: [value]\n - id: atan2-left-down\n name: The angle of a point to the left\n pattern: y x atan2\n when:\n x: [isNegativeConstant]\n y: [isNegativeConstant]\n output: y x / arctan =pi -\n explain: "For x < 0 and y < 0, atan2(y, x) = arctan(y/x) - π."\n tags: [value]\n - { id: atan2-negative-axis, name: The angle of a point on the negative axis, pattern: 0 x atan2, when: { x: [isNegativeConstant] }, output: =pi, tags: [value], explain: "A point on the negative x-axis is at angle π." }\n - { id: atan2-up, name: Straight up, pattern: y 0 atan2, when: { y: [isPositiveConstant] }, output: =pi 2 /, tags: [value], explain: "A point straight up is at angle π/2." }\n - { id: atan2-down, name: Straight down, pattern: y 0 atan2, when: { y: [isNegativeConstant] }, output: =pi 2 / neg, tags: [value], explain: "A point straight down is at angle -π/2." }\n\n # the odd inverses take the sign out; arccos(-u) = π - arccos u\n - id: arcsin-odd\n name: Arcsine of a negative\n pattern: u arcsin\n when:\n u: [hasMinusSign]\n output: u neg arcsin neg\n explain: "arcsin(-x) = -arcsin x."\n tags: [symmetry]\n\n - id: arctan-odd\n name: Arctangent of a negative\n pattern: u arctan\n when:\n u: [hasMinusSign]\n output: u neg arctan neg\n explain: "arctan(-x) = -arctan x."\n tags: [symmetry]\n\n - id: arccos-negative\n name: Arccosine of a negative\n pattern: u arccos\n when:\n u: [hasMinusSign]\n output: =pi u neg arccos -\n explain: "arccos(-x) = π - arccos x."\n tags: [symmetry]\n\n # ---- trigonometry: identities --------------------------------------------\n - id: pythagorean\n name: sin² + cos² = 1\n pattern: u sin 2 ^ u cos 2 ^ +\n commutative: true\n output: "1"\n explain: "sin²{u} + cos²{u} = 1 for every angle."\n tags: [identity]\n\n - id: pythagorean-multiple\n name: sin² + cos² = 1\n pattern: a u sin 2 ^ * a u cos 2 ^ * +\n commutative: true\n output: a\n explain: "{a}·sin²{u} + {a}·cos²{u} = {a}(sin²{u} + cos²{u}) = {a}."\n tags: [identity]\n\n - id: one-minus-sin-squared\n name: 1 - sin² = cos²\n pattern: u sin 2 ^ neg 1 +\n output: u cos 2 ^\n explain: "1 - sin²{u} = cos²{u}."\n tags: [identity]\n\n - id: one-minus-cos-squared\n name: 1 - cos² = sin²\n pattern: u cos 2 ^ neg 1 +\n output: u sin 2 ^\n explain: "1 - cos²{u} = sin²{u}."\n tags: [identity]\n\n - id: sin-over-cos\n name: sin/cos is tan\n pattern: u sin u cos /\n output: u tan\n explain: "sin {u} / cos {u} = tan {u}."\n tags: [identity]\n\n - id: cos-over-sin\n name: cos/sin is cot\n pattern: u cos u sin /\n output: u cot\n explain: "cos {u} / sin {u} = cot {u}."\n tags: [identity]\n\n - id: sin-arcsin\n name: sin undoes arcsin\n pattern: u arcsin sin\n output: u\n explain: "sin(arcsin {u}) = {u}."\n tags: [inverse]\n\n - id: cos-arccos\n name: cos undoes arccos\n pattern: u arccos cos\n output: u\n explain: "cos(arccos {u}) = {u}."\n tags: [inverse]\n\n - id: tan-arctan\n name: tan undoes arctan\n pattern: u arctan tan\n output: u\n explain: "tan(arctan {u}) = {u}."\n tags: [inverse]\n\n - id: cosh-squared-minus-sinh-squared\n name: cosh² - sinh² = 1\n pattern: u cosh 2 ^ u sinh 2 ^ -\n output: "1"\n explain: "cosh²{u} - sinh²{u} = 1."\n tags: [identity]\n\n # ---- logs: opt-in rewrites (run with cas.rewrite(x, \'expand-log\') or \'combine-log\') ----\n - id: ln-product\n name: Log of a product\n mode: expand-log\n pattern: a b * ln\n output: a ln b ln +\n explain: "ln({a}·{b}) = ln {a} + ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-quotient\n name: Log of a quotient\n mode: expand-log\n pattern: a b / ln\n output: a ln b ln -\n explain: "ln({a}/{b}) = ln {a} - ln {b} (for positive {a}, {b})."\n tags: [log]\n\n - id: ln-power\n name: Log of a power\n mode: expand-log\n pattern: a n ^ ln\n output: n a ln *\n explain: "ln({a}^{n}) = {n}·ln {a} (for positive {a})."\n tags: [log]\n\n - id: ln-root\n name: Log of a square root\n mode: expand-log\n pattern: a sqrt ln\n output: a ln 2 /\n explain: "ln √{a} = ½ ln {a}."\n tags: [log]\n\n - id: ln-sum-combine\n name: Sum of logs\n mode: combine-log\n pattern: a ln b ln +\n commutative: true\n output: a b * ln\n explain: "ln {a} + ln {b} = ln({a}·{b})."\n tags: [log]\n\n - id: ln-difference-combine\n name: Difference of logs\n mode: combine-log\n pattern: a ln b ln -\n output: a b / ln\n explain: "ln {a} - ln {b} = ln({a}/{b})."\n tags: [log]\n\n - id: ln-multiple-combine\n name: A multiple of a log\n mode: combine-log\n pattern: n a ln *\n when:\n n: [isRational]\n output: a n ^ ln\n explain: "{n}·ln {a} = ln({a}^{n})."\n tags: [log]\n','name: Solving by undoing\n\n# mode: isolate. Each rule undoes the outermost function on the side with the\n# unknown: ln u = r → u = e^r. The predicates hasVariable and freeOfVariable mean\n# "mentions / doesn\'t mention the unknown being solved for".\n#\n# The CAS does the rest itself: it moves terms without the unknown to the other\n# side, divides by a coefficient, and when the unknown appears in several places\n# it uses the polynomial methods (factoring, the quadratic formula) or splits a\n# product equal to 0. Every answer is checked in the original equation, so a\n# rule may give extra candidates (squaring both sides does): the wrong ones are\n# dropped, with a step saying so.\n#\n# An output can give several answers: `pm` (±) splits into two, and so does\n# `|` (or): "u r arcsin = u =pi r arcsin - = |".\n\nrules:\n - id: iso-swap\n name: Unknown on the left\n mode: isolate\n pattern: l r =\n when:\n l: [freeOfVariable]\n r: [hasVariable]\n output: r l =\n priority: 20\n explain: "Swap the sides so the unknown is on the left."\n tags: [tidy]\n\n - id: iso-ln\n name: Undo the log\n mode: isolate\n pattern: u ln r =\n when:\n u: [hasVariable]\n output: u =e r ^ =\n explain: "Raise e to each side: e^(ln {u}) = {u}."\n tags: [inverse]\n\n - id: iso-log\n name: Undo the log\n mode: isolate\n pattern: b u log r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r ^ =\n explain: "Raise {b} to each side: {b}^(log base {b} of {u}) = {u}."\n tags: [inverse]\n\n - id: iso-exp\n name: Undo e to a power\n mode: isolate\n pattern: =e u ^ r =\n when:\n u: [hasVariable]\n output: u r ln =\n explain: "Take ln of each side: ln(e^{u}) = {u}."\n tags: [inverse]\n\n - id: iso-exponential\n name: Undo a power of a number\n mode: isolate\n pattern: b u ^ r =\n when:\n u: [hasVariable]\n b: [freeOfVariable]\n output: u b r log =\n explain: "Take the log to base {b} of each side."\n tags: [inverse]\n\n - id: iso-square\n name: Undo the square\n mode: isolate\n pattern: u 2 ^ r =\n when:\n u: [hasVariable]\n output: u r sqrt pm =\n priority: 1\n explain: "Take the square root of each side; {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-even-power\n name: Undo an even power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isEvenWhole]\n output: u r 1 n / ^ pm =\n explain: "Take the root of each side (the {n}th root); {u} can be positive or negative."\n tags: [inverse]\n\n - id: iso-odd-power\n name: Undo an odd power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isOddWhole]\n output: u r 1 n / ^ =\n explain: "Take the root of each side (the {n}th root)."\n tags: [inverse]\n\n - id: iso-fractional-power\n name: Undo a power\n mode: isolate\n pattern: u n ^ r =\n when:\n u: [hasVariable]\n n: [isRational]\n output: u r 1 n / ^ =\n priority: -1\n explain: "Raise each side to the power 1/{n}."\n tags: [inverse]\n\n - id: iso-sqrt\n name: Undo the square root\n mode: isolate\n pattern: u sqrt r =\n when:\n u: [hasVariable]\n output: u r 2 ^ =\n explain: "Square each side (this can add answers, so each one is checked at the end)."\n tags: [inverse]\n\n - id: iso-root\n name: Undo the root\n mode: isolate\n pattern: n u root r =\n when:\n u: [hasVariable]\n n: [freeOfVariable]\n output: u r n ^ =\n explain: "Raise each side to the power {n}."\n tags: [inverse]\n\n - id: iso-reciprocal\n name: Undo the fraction\n mode: isolate\n pattern: c u / r =\n when:\n u: [hasVariable]\n c: [freeOfVariable]\n output: u c r / =\n explain: "{c}/{u} = {r}, so {u} = {c}/{r}."\n tags: [inverse]\n\n - id: iso-abs\n name: Undo the absolute value\n mode: isolate\n pattern: u abs r =\n when:\n u: [hasVariable]\n output: u r pm =\n explain: "|{u}| = {r} means {u} is {r} or -{r}."\n tags: [inverse]\n\n - id: iso-sin\n name: Undo the sine\n mode: isolate\n pattern: u sin r =\n when:\n u: [hasVariable]\n output: u r arcsin = u =pi r arcsin - = |\n explain: "Two angles in a turn have sine {r}: arcsin {r} and π - arcsin {r} (add any whole number of turns, 2πk, for the rest)."\n tags: [inverse, trig]\n\n - id: iso-cos\n name: Undo the cosine\n mode: isolate\n pattern: u cos r =\n when:\n u: [hasVariable]\n output: u r arccos pm =\n explain: "Two angles in a turn have cosine {r}: ±arccos {r} (add 2πk for the rest)."\n tags: [inverse, trig]\n\n - id: iso-tan\n name: Undo the tangent\n mode: isolate\n pattern: u tan r =\n when:\n u: [hasVariable]\n output: u r arctan =\n explain: "Take arctan of each side (add πk for the rest)."\n tags: [inverse, trig]\n\n - { id: iso-arcsin, name: Undo arcsin, mode: isolate, pattern: u arcsin r =, when: { u: [hasVariable] }, output: u r sin =, tags: [inverse], explain: "Take sin of each side." }\n - { id: iso-arccos, name: Undo arccos, mode: isolate, pattern: u arccos r =, when: { u: [hasVariable] }, output: u r cos =, tags: [inverse], explain: "Take cos of each side." }\n - { id: iso-arctan, name: Undo arctan, mode: isolate, pattern: u arctan r =, when: { u: [hasVariable] }, output: u r tan =, tags: [inverse], explain: "Take tan of each side." }\n - { id: iso-sinh, name: Undo sinh, mode: isolate, pattern: u sinh r =, when: { u: [hasVariable] }, output: u r arcsinh =, tags: [inverse], explain: "Take arcsinh of each side." }\n - { id: iso-tanh, name: Undo tanh, mode: isolate, pattern: u tanh r =, when: { u: [hasVariable] }, output: u r arctanh =, tags: [inverse], explain: "Take arctanh of each side." }\n - { id: iso-cosh, name: Undo cosh, mode: isolate, pattern: u cosh r =, when: { u: [hasVariable] }, output: u r arccosh pm =, tags: [inverse], explain: "Two numbers have cosh {r}: ±arccosh {r}." }\n - { id: iso-arcsinh, name: Undo arcsinh, mode: isolate, pattern: u arcsinh r =, when: { u: [hasVariable] }, output: u r sinh =, tags: [inverse], explain: "Take sinh of each side." }\n - { id: iso-arccosh, name: Undo arccosh, mode: isolate, pattern: u arccosh r =, when: { u: [hasVariable] }, output: u r cosh =, tags: [inverse], explain: "Take cosh of each side." }\n - { id: iso-arctanh, name: Undo arctanh, mode: isolate, pattern: u arctanh r =, when: { u: [hasVariable] }, output: u r tanh =, tags: [inverse], explain: "Take tanh of each side." }\n'],Tr=['name: Complex numbers\n\n# Loaded only by createCAS({ complex: true }), where i is the imaginary unit.\n# The arithmetic (i² = -1, √-4 = 2i, (2 + 3i)(1 - i) = 5 + i, 1/(1 + i) = (1 - i)/2)\n# and Re, Im, conj, arg, |z| are the normal form\'s (src/cas/form.js); unknowns\n# count as real, so Re(x + 3i) = x. Write a complex unknown as a + bi.\n\noperators:\n - { symbol: re, arity: 1, label: real part }\n - { symbol: im, arity: 1, label: imaginary part }\n - { symbol: conj, arity: 1, label: complex conjugate }\n - { symbol: arg, arity: 1, label: argument }\n\nrules:\n - id: euler\n name: Euler\'s formula\n pattern: =e u ^\n when:\n u: [hasImaginaryPart, isConstant]\n output: =e u re ^ u im cos =i u im sin * + *\n explain: "e^(a + bi) = e^a (cos b + i sin b)."\n tags: [complex]\n\n - id: ln-negative\n name: Log of a negative number\n pattern: u ln\n when:\n u: [isNegativeConstant]\n output: u neg ln =i =pi * +\n explain: "{u} = |{u}|·e^(iπ), so ln {u} = ln |{u}| + iπ (the principal value)."\n tags: [complex]\n\n - id: ln-complex\n name: Log of a complex number\n pattern: u ln\n when:\n u: [hasImaginaryPart, isConstant]\n output: u abs ln u arg =i * +\n explain: "ln z = ln |z| + i arg z (the principal value)."\n tags: [complex]\n\n - id: i-to-the-i\n name: i to the power i\n pattern: =i =i ^\n output: =e =pi 2 / neg ^\n explain: "i = e^(iπ/2), so i^i = e^(i·iπ/2) = e^(-π/2) (the principal value)."\n tags: [complex]\n'],jr={normal:"Work out the numbers and collect like terms.","simplify.cancel":"Cancel the factors the top and bottom share.","simplify.expand":"Multiplying out gives something shorter.","simplify.factor":"Factoring gives something shorter.",expand:"Multiply out the brackets.",factor:"Write it as a product of factors.","factor.common":"Take out the common factor {common}.","factor.polynomial":"Factor what is left: {roots}.",together:"Write it as one fraction over a common denominator.",cancel:"Cancel the factors the top and bottom share: {cancelled}.","solve.move":"Keep the terms with {v} on the left and move the others to the right.","solve.divide":"Divide both sides by {by}.","solve.multiply":"Multiply both sides by {by}.","solve.one-side":"Move everything to one side, so the equation reads … = 0.","solve.factor":"Factor the left side.","solve.zero-product":"A product is 0 exactly when one of its factors is 0.","solve.split":"There are two cases; solve each.","solve.quadratic":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a, and b² - 4ac = {D}.","solve.no-real":"b² - 4ac = {D} is negative, so there are no real solutions.","solve.quadratic-complex":"The quadratic formula with a = {a}, b = {b}, c = {c}: {v} = (-b ± √(b² - 4ac)) / 2a. b² - 4ac = {D} is negative, so its square root is imaginary: √({D}) = {root}.","solve.roots":"{v}^{n} = {r} has {n} solutions, spaced evenly round a circle: |{r}|^(1/{n})·(cos θ + i sin θ), with θ = (arg {r} + 2πk)/{n} for k = 0 … {last}.","solve.clear-denominator":"Multiply both sides by {den} (an answer that makes it 0 is not allowed).","solve.substitute":"Write {u} for {kernel}: this is a polynomial in {u}.","solve.reject":"{value} is not a solution: {reason}.","solve.always":"This is true for every {v}.","solve.never":"This is never true, so there is no solution.","solve.unsolved":"There is no exact method here for solving for {v}; try { approximate: true }.","solve.numeric":"Found {count} solution(s) numerically.","system.eliminate":"Use one equation to remove {v} from the others.","integrate.expand":"Multiply out, then integrate term by term.","integrate.substitute":"Let {u} = {inside}, so d{u} = {a} d{v}.","integrate.back":"Put {inside} back for {u}.","integrate.parts":"By parts with u = {u} and dv = {dv} d{v}: ∫ u dv = u·v - ∫ v du, where v = {V} and du = {du} d{v}.","integrate.constant":"The number {c} comes out of the integral.","integrate.divide":"The top has at least the degree of the bottom: divide first.","integrate.partial-fractions":"Split the fraction into simple fractions, one for each factor below.","integrate.evaluate":"Evaluate {F} at {b} and at {a}, and subtract.",substitute:"Put in the values."},Zr=["normal","rewrite","simplify","expand","factor","cancel","diff","differentiate","integrate","solve","solveSystem","substitute","approximate","equivalent"];class zr{constructor(e,n,t,r,o){this.set=e,this.messages=n,this.format=t,this.read=r,this.complex=o;for(const e of Zr){const n=zr.prototype[e];this[e]=(...e)=>J(o,()=>n.apply(this,e))}}node(e){if(e&&"object"==typeof e&&!Array.isArray(e)&&e.type)return e;if(Array.isArray(e))return I(e);if("string"!=typeof e)throw new D("expected an expression");if(this.read){const n=this.read(e);return Array.isArray(n)?I(n):"string"==typeof n?A(n):n}return A(e)}step(e,n,t,r,o,s={}){return function(e,n,t,r,o,s,i,a,u=[]){const l=(s??"").replace(/\{(\w+)\}/g,(e,n)=>{const t=i?.[n];return void 0===t?e:"string"==typeof t?t:a(t)});return{id:e,name:n,tags:t,from:r.s,to:o.s,path:u,before:r.s,after:o.s,explanation:l}}(e,n,t,r,o,this.messages[e]??"",s,this.format)}result(e,n,t,r={}){let o=e;if(t.approximate&&o){o=ft(o,{digits:"number"==typeof t.approximate?t.approximate:15})}return{result:o,text:o?this.format(o):"",steps:At(n,Nt(t.steps)),...r}}variable(e,n){if(n)return n;const t=[...Fe(e)];return 1===t.length?t[0]:t.includes("x")?"x":t[0]??"x"}tidyStep(e,n){return e.s===n.s?[]:[this.step("normal","Work out and collect",["tidy","arithmetic"],e,n)]}normal(e){return Te(this.node(e))}rewrite(e,n,t={}){const r=this.node(e),o=this.set.view(n);if(!o.size)throw new D(`no rules in mode "${n}" (modes: ${this.set.modes().join(", ")})`);const s=$t(r,o,{format:this.format,order:t.order,variable:t.variable});return this.result(s.node,[...this.tidyStep(r,Te(r)),...s.steps],t)}simplify(e,n={}){const t=this.node(e),r=[...this.tidyStep(t,Te(t))],o=$t(t,this.set.view("simplify"),{format:this.format});r.push(...o.steps);let s=o.node,i=null;const a=Ee(s),u=[],l=0===Fe(s).size,c=l?null:Kt(a);c&&u.push({node:Jt(c),id:"simplify.cancel",name:"Cancel"});const f=$t(De(Et(a)),this.set.view("simplify"),{format:this.format});u.push({node:f.node,id:"simplify.expand",name:"Multiply out"}),"add"!==a.k||l||u.push({node:Jt(Ut(a)),id:"simplify.factor",name:"Factor"});for(const e of u)E(e.node)<E(s)&&(i=this.step(e.id,e.name,["shorter"],s,e.node),s=e.node);return i&&r.push(i),this.result(s,r,n)}expand(e,n={}){const t=this.node(e),r=De(Et(Ee(t)));return this.result(r,t.s===r.s?[]:[this.step("expand","Multiply out",["expand"],t,r)],n)}factor(e,n={}){const t=this.node(e),r=Ut(Ee(t)),o=Jt(r),s=[],i=r.notes.find(e=>"factor.common"===e.id);return o.s!==Te(t).s&&s.push(this.step(i?"factor.common":"factor","Factor",["factor"],t,o,i?{common:De(i.values.common)}:{})),this.result(o,s,n)}cancel(e,n={}){const t=this.node(e),r=Ee(t),o=Kt(r);if(!o)return this.result(Te(t),this.tidyStep(t,Te(t)),n);const s=Jt(o),i=Yt(r),a=S("/",[De(i.num),De(i.den)]),u=[];return"/"===t.op&&a.s===Te(t).s||u.push(this.step("together","One fraction",["together"],t,a)),s.s!==a.s&&u.push(this.step("cancel","Cancel",["cancel"],a,s,{cancelled:o.cancelled.length?o.cancelled.map(e=>this.format(De(e))).join(", "):"numbers"})),this.result(s,u,n)}diff(e,n,t={}){const r=this.node(e),o=this.variable(r,n);let s=r;const i=[];for(let e=0;e<(t.order??1);e++){const e=$t(S("der",[s,x(o)]),this.set.view("differentiate"),{format:this.format,order:"pre"}),n=$t(e.node,this.set.view("simplify"),{format:this.format});i.push(...e.steps,...n.steps),s=n.node}return this.result(s,i,t,{variable:o})}differentiate(e,n){const t=$t(S("der",[e,x(n)]),this.set.view("differentiate"),{format:this.format,order:"pre"});return $t(t.node,this.set.view("simplify"),{format:this.format}).node}integrate(e,n,t={}){let r=this.node(e);const o=e=>void 0===e?null:this.node("number"==typeof e?String(e):e);let s=o(t.from),i=o(t.to);if(N(r)&&"int"===r.op){const[e,t,o,a]=r.args;n=t.token,o&&a&&(s=o,i=a),r=e}const a=this.variable(r,n),u=br(this,r,a),l=$t(u.node,this.set.view("simplify"),{format:this.format}),c=[...u.steps,...l.steps];if(s&&i){const e=qr(this,l.node,a,s,i,r);c.push(e.step);const n=$t(e.value,this.set.view("simplify"),{format:this.format});return c.push(...n.steps),this.result(n.node,c,t,{antiderivative:l.node,variable:a})}let f=l.node;return t.constant&&(f=S("+",[f,x(String(t.constant))])),this.result(f,c,t,{variable:a})}solve(e,n,t={}){const r=this.node(e),o=this.variable(r,n),s=nr(this,r,o,t);let i=s.solutions;if(t.approximate){const e="number"==typeof t.approximate?t.approximate:15;i=i.map(n=>ft(n,{digits:e}))}const a=i.map(e=>S("=",[x(o),e])),u=a.length?a.reduce((e,n)=>e?S("|",[e,n]):n,null):null;return{solutions:i,result:u,variable:o,text:s.always?`true for every ${o}`:u?this.format(u):s.unsolved.length?`no exact solution found for ${o}`:"no solution",unsolved:s.unsolved.filter(e=>!e.always),always:s.always,steps:At(s.steps,Nt(t.steps))}}solveSystem(e,n,t={}){const r=e.map(e=>this.node(e)),o=n??[...new Set(r.flatMap(e=>[...Fe(e)]))].sort(),s=function(e,n,t){const r=[],o=n.map(n=>{const r=er(n)?pe([Ee(n.args[0]),Se(Ee(n.args[1]))]):Ee(n),o=t.map(n=>{const t=jt(r,n);if(!t||Math.max(0,...t.keys())>1)throw new D(`not linear in ${n}`);const o=t.get(1)??K(R.ZERO);if(!ne(o))throw new D(`the coefficient of ${n} must be a number (it is ${e.format(De(o))})`);return o.q});let s=r;for(let e=0;e<t.length;e++)s=pe([s,he([K(o[e].neg()),Ee(x(t[e]))])]);for(const e of t)if(Zt(s,e))throw new D(`not linear in ${e}`);return{coeffs:o,rhs:Se(s)}}),s=()=>o.map(e=>Gt(De(pe(e.coeffs.map((e,n)=>he([K(e),Ee(x(t[n]))])))),De(e.rhs))).reduce((e,n)=>e?S("&",[e,n]):n,null);let i=0;const a=[];for(let n=0;n<t.length&&i<o.length;n++){const u=o.findIndex((e,t)=>t>=i&&!e.coeffs[n].isZero);if(u<0)continue;[o[i],o[u]]=[o[u],o[i]];const l=s(),c=o[i],f=c.coeffs[n];c.coeffs=c.coeffs.map(e=>e.div(f)),c.rhs=he([K(f.inv()),c.rhs]);for(let e=0;e<o.length;e++){if(e===i||o[e].coeffs[n].isZero)continue;const t=o[e].coeffs[n];o[e].coeffs=o[e].coeffs.map((e,n)=>e.sub(t.mul(c.coeffs[n]))),o[e].rhs=pe([o[e].rhs,he([K(t.neg()),c.rhs])])}r.push(e.step("system.eliminate","Eliminate",["eliminate"],l,s(),{v:x(t[n])})),a.push(n),i++}for(const e of o.slice(i))if(!ne(e.rhs)||!e.rhs.q.isZero)return{solution:null,steps:r,status:"none"};if(a.length<t.length)return{solution:null,steps:r,status:"many"};const u=new Map;return a.forEach((e,n)=>u.set(t[e],De(o[n].rhs))),{solution:u,steps:r,status:"one"}}(this,r,o),i=s.solution?Object.fromEntries([...s.solution].map(([e,n])=>[e,n])):null,a="one"===s.status?o.map(e=>`${e} = ${this.format(i[e])}`).join(", "):"none"===s.status?"no solution":"infinitely many solutions";return{solution:i,status:s.status,text:a,steps:At(s.steps,Nt(t.steps))}}substitute(e,n,t={}){const r=this.node(e);let o=r;for(const[e,t]of Object.entries(n))o=sr(o,e,"number"==typeof t?this.node(String(t)):this.node(t));const s=this.simplify(o,t),i=[this.step("substitute","Substitute",["substitute"],r,o)];return{...s,steps:[...At(i,Nt(t.steps)),...s.steps]}}defined(e){const n=this.set.view("define");return n.size?$t(e,n,{format:this.format}).node:e}approximate(e,n={}){const t=this.defined(this.node(e));if(Fe(t).size&&!n.scope){const e=ft(Te(t),n);return{result:e,text:this.format(e),number:null,exact:!1}}const r=ut(t,n);return{result:r.node,text:r.text,number:r.number,re:r.re,im:r.im,exact:r.exact}}equivalent(e,n){const t=this.node(e),r=this.node(n),o=this.defined(S("-",[t,r])),s=this.simplify(o,{steps:!1}).result;if("num"===s.type&&"0"===s.token)return{equal:!0,how:"exact"};const i=[...Fe(o)];if(!i.length)try{return{equal:Math.abs(ut(o,{digits:30}).number)<1e-25,how:"numeric"}}catch{return{equal:!1,how:"numeric"}}const a=[.31,1.7,2.9,-.83,.57];let u=0;for(let e=0;e<a.length;e++){const n=Object.fromEntries(i.map((n,t)=>[n,String(a[(e+t)%a.length]+t/7)]));let t;try{t=ut(o,{digits:30,scope:n}).number}catch{continue}if(u++,Math.abs(t)>1e-20)return{equal:!1,how:"numeric"}}return{equal:u>0,how:"numeric"}}modes(){return this.set.modes()}}function Dr(e={}){const n=!1===e.defaults?[]:[...Er,...e.complex?Tr:[]],{specs:t,messages:r}=function(e){bt();const n=[],t={};for(const r of e){const e="string"==typeof r?yn(r):r,o=Array.isArray(e)?e:e?.rules??[];for(const n of(Array.isArray(e)?[]:e?.operators)??[]){if(!n?.symbol)throw new Error("an operator needs a symbol");p(n.symbol)||l({symbol:String(n.symbol),arity:"any"===n.arity?i:Number(n.arity),label:n.label})}Object.assign(t,(Array.isArray(e)?null:e?.messages)??{});for(const e of o)n.push(e)}return{specs:n,messages:t}}([...n,...e.rules??[]]),o=J(e.complex,()=>yt(t));return new zr(o,{...jr,...r},e.format??Sr,e.read??null,Boolean(e.complex))}const Br=Symbol.for("inlinemath.expressions"),Cr=new Map,Fr={re:"Re",im:"Im",conj:"overline"},Vr=["Re","Im","re","im","conj","arg"];function Rr(e){const t=[],r=e=>{"op"===e.type?(e.args.forEach(r),n(e.op)?(-1===n(e.op).arity&&t.push(String(e.args.length)),t.push(e.op)):t.push(String(e.args.length),`\\:${Fr[e.op]??e.op}`)):t.push(e.token)};return r(e),t}function Ur(n={}){const t=n.rules||n.names?null:n.complex?"complex":"default";if(t&&Cr.has(t))return Cr.get(t);const r=[...n.names??[],...n.complex?Vr:[]],o=Dr({...n,read:n=>e(n,r.length?{names:r}:{}),format:Sr});return t&&Cr.set(t,o),o}const Pr=new Set(["simplify","expand","factor","cancel","diff","integrate","solve","approx"]),Lr={integral:"integrate",differentiate:"diff",approximate:"approx",simp:"simplify"};function Wr(e={}){const n=e.cas??Ur(),o=void 0===e.steps?{}:{steps:e.steps},s=(e,i)=>{let a;try{a=n.read(e)}catch{return t(e,i)}const u=i&&i[Br];u&&(a=a.flatMap(e=>Object.hasOwn(u,e)?u[e]:[e]));const l=a[a.length-1],c=l?.startsWith("\\:")?Lr[l.slice(2)]??l.slice(2):null,f=c&&Pr.has(c);if(!f&&!("der"===l||"int"===l))return t(e,i);const p=n.node(a),d=f?p.args:[p],h=e=>e?e.s:void 0;let m;try{switch(f?c:"der"===l?"derivative":"antiderivative"){case"simplify":m=n.simplify(d[0],o);break;case"expand":m=n.expand(d[0],o);break;case"factor":m=n.factor(d[0],o);break;case"cancel":m=n.cancel(d[0],o);break;case"diff":m=n.diff(d[0],h(d[1]),{...o,order:d[2]?Number(d[2].s):1});break;case"integrate":m=n.integrate(d[0],h(d[1]),{...o,...d[3]?{from:d[2].s,to:d[3].s}:{}});break;case"solve":m=n.solve(d[0],h(d[1]),o);break;case"approx":m=n.approximate(d[0],{...o,digits:d[1]?Number(d[1].s):15});break;case"derivative":m=n.diff(p.args[0],p.args[1].s,o);break;default:m=n.integrate(p,void 0,o)}}catch(n){return`(${e})`}if(s.last=m,!m.result)return`"${m.text}"`;const g=r(Rr(m.result));return/^-?\d+(\.\d+)?$/.test(g)?g:`(${g})`};return s}const _r=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function Hr(e,n={}){return`<ol class="mv-steps">${e.map(e=>{const t=Rr(A(e.from)),r=o(t,{...n,highlight:e.path&&e.path.length?{path:e.path}:void 0}),s=e.to===e.from?"":`<span class="mv-step-arrow" aria-label="becomes">⟶</span>${o(Rr(A(e.to)),n)}`,i=e.explanation?`<p class="mv-step-why">${_r(e.explanation)}</p>`:"";return`<li class="mv-step" data-rule="${_r(e.id)}"><span class="mv-step-name">${_r(e.name)}</span><div class="mv-step-maths">${r}${s}</div>${i}</li>`}).join("")}</ol>`}export{Wr as casBlocks,Ur as mathCAS,Hr as stepsHTML,Rr as tokensOf};
|