@mathzetta/inlinemath 0.4.0 → 0.4.2

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.
@@ -1,2 +1,2 @@
1
- /* Inline Math 0.4.0 — MIT license; MathZetta not included: map mathzetta, mathzetta/speech and mathzetta/calculate (and mathzetta/text, for cas.external.js) with an import map */
2
- import{parse as e,operator as n,fromPostfix as t,walk as s}from"mathzetta";import"mathzetta/speech";import{calculateBlock as i}from"mathzetta/calculate";import{toText as r}from"mathzetta/text";import{a as o}from"./chunks/html-6HJlblNm.js";import"./chunks/draw-Bw547gEd.js";const a=new Map,u=-1,l="\\:",c=e=>"string"==typeof e&&e.startsWith(l)&&e.length>2;function f(e){if(!e||!e.symbol)throw new Error("operator needs a symbol");if(!Number.isInteger(e.arity)||e.arity<0&&e.arity!==u)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 a.set(n.symbol,n),n}const p=Object.freeze({symbol:l,arity:u,commutative:!1,fold:null,label:"function"});function h(e){const n=a.get(e);return n||(c(e)?{...p,symbol:e,label:e.slice(2)}:null)}function d(e){return a.has(e)||c(e)}const m=e=>Number.isFinite(e)&&Number.isInteger(e)?e:null,g=e=>Number.isFinite(e)?e:null;!function(){f({symbol:"+",arity:2,commutative:!0,label:"add",fold:(e,n)=>g(e+n)}),f({symbol:"-",arity:2,label:"subtract",fold:(e,n)=>g(e-n)}),f({symbol:"*",arity:2,commutative:!0,label:"multiply",fold:(e,n)=>g(e*n)}),f({symbol:"/",arity:2,label:"divide",fold:(e,n)=>0===n?null:m(e/n)}),f({symbol:"^",arity:2,label:"power",fold:(e,n)=>Number.isInteger(n)&&Math.abs(n)<=64?g(e**n):null}),f({symbol:"neg",arity:1,label:"negate",fold:e=>g(-e)}),f({symbol:"pm",arity:1,label:"plus or minus"}),f({symbol:"±",arity:2,label:"plus or minus"}),f({symbol:"mod",arity:2,label:"modulo",fold:(e,n)=>0===n?null:m((e%n+n)%n)}),f({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}),f({symbol:"_",arity:2,label:"subscript"}),f({symbol:"der",arity:2,label:"derivative"}),f({symbol:"evaluated",arity:4,label:"evaluated from a to b"}),f({symbol:"setbuilder",arity:2,label:"the set of … such that"}),f({symbol:"int",arity:u,label:"integral"}),f({symbol:"lim",arity:u,label:"limit"}),f({symbol:"\\sumidx",arity:u,label:"sum over an index"}),f({symbol:"\\prodidx",arity:u,label:"product over an index"}),f({symbol:"abs",arity:1,label:"absolute value",fold:e=>g(Math.abs(e))}),f({symbol:"floor",arity:1,label:"floor",fold:e=>g(Math.floor(e))}),f({symbol:"ceil",arity:1,label:"ceiling",fold:e=>g(Math.ceil(e))}),f({symbol:"round",arity:2,label:"round",fold:(e,n)=>Number.isInteger(n)?g(Math.round(e*10**n)/10**n):null}),f({symbol:"fixed",arity:2,label:"fixed",fold:()=>null}),f({symbol:"sqrt",arity:1,label:"square root",fold:e=>m(Math.sqrt(e))}),f({symbol:"root",arity:2,label:"nth root",fold:(e,n)=>m(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","arcsec","arccsc","arccot","arcsinh","arccosh","arctanh","ln","loglog","logloglog","expm1"])f({symbol:e,arity:1,label:e});f({symbol:"log",arity:2,label:"log to a base"}),f({symbol:"atan2",arity:2,label:"atan2"}),f({symbol:"perm",arity:2,label:"permutations"}),f({symbol:"comb",arity:2,label:"combinations"}),f({symbol:"random",arity:0,label:"random"});for(const e of["max","min","gcd","mean","sum","prod"])f({symbol:e,arity:u,label:e});for(const e of["()","[]","{}","(]","[)"])f({symbol:e,arity:u,label:"group"});for(const e of["pmatrix","bmatrix","vmatrix"])f({symbol:e,arity:u,label:"matrix"});f({symbol:"det",arity:1,label:"determinant"});for(const e of["=","===","≠","≠=","<",">","≤","≥","∈","∉","∪","∩","≈","≡","→","pmod","&","|","\\xor","\\nand","\\nor","\\implies","\\iff"])f({symbol:e,arity:2,label:e});f({symbol:"\\not",arity:1,label:"not"}),f({symbol:"?:",arity:3,label:"if then else"})}();const v="num",b="sym",w="op",y=Object.freeze([]);class x extends Error{constructor(e){super(e),this.name="ExprError"}}function q(e){if("number"!=typeof e||!Number.isFinite(e))throw new x(`not a finite number: ${e}`);const n=(t=e,Object.is(t,-0)?"0":String(t));var t;return Object.freeze({type:v,token:n,value:e,args:y,s:n})}function k(e){if("string"!=typeof e||""===e)throw new x("symbol needs a non-empty token");return Object.freeze({type:b,token:e,value:null,args:y,s:e})}function $(e){const n=/^(-?)0*(\d+?)(?:\.(\d*?)0*)?$/.exec(String(e));if(!n)throw new x(`not an exact decimal: ${e}`);const[,t,s,i=""]=n,r=i?`${s}.${i}`:s,o=/^0(\.0*)?$/.test(r)?"0":t+r;return Object.freeze({type:v,token:o,value:Number(o),args:y,s:o})}const S=/^-?\d+(\.\d+)?$/;function M(e){const n=String(e);if(S.test(n))return $(n);if(""!==n&&!/\s/.test(n)){const e=Number(n);if(Number.isFinite(e))return q(e)}return k(n)}function N(e,n){const t=h(e);if(!t)throw new x(`unknown operator "${e}"`);if(t.arity!==u&&n.length!==t.arity)throw new x(`"${e}" takes ${t.arity} operand(s), got ${n.length}`);const s=Object.freeze(n.slice()),i=t.arity===u?` ${s.length}`:"",r=`${s.length?s.map(e=>e.s).join(" "):""}${s.length,""}${i} ${e}`.trimStart();return Object.freeze({type:w,op:e,token:e,value:null,args:s,s:r})}const O=e=>e.type===v,A=e=>e.type===w;function I(e){return E(function(e){const n=String(e).trim();return""===n?[]:n.split(/\s+/)}(e))}function E(e){if(!Array.isArray(e))throw new x("fromPostfix needs an array of tokens");if(0===e.length)throw new x("empty expression");const n=[];for(let t=0;t<e.length;t++){const s=String(e[t]);if(d(s)){let e=h(s).arity;if(e===u){const i=n.pop();if(e=i&&i.type===v&&Number.isInteger(i.value)&&i.value>=0?i.value:-1,e<0)throw new x(`"${s}" at position ${t+1} takes any number of operands, so a count must come before it`)}if(n.length<e)throw new x(`"${s}" at position ${t+1} needs ${e} operand(s), only ${n.length} on the stack`);const i=n.splice(n.length-e,e);n.push(N(s,i))}else n.push(M(s))}if(1!==n.length){const t=[...new Set(e.filter(e=>!d(e)))];throw new x(`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 T(e){if(e.type!==w)return 0;let n=0;for(const t of e.args)n=Math.max(n,T(t));return n+1}function j(e){if(e.type!==w)return 1;let n=1;for(const t of e.args)n+=j(t);return n}function z(e,n=[]){if(e.type!==w)n.push(e.token);else for(const t of e.args)z(t,n);return n}function Z(e){return e.type===v||e.type!==b&&e.args.every(Z)}function F(e,n="pre",t=[],s=[]){"pre"===n&&s.push({node:e,path:t});for(let i=0;i<e.args.length;i++)F(e.args[i],n,t.concat(i),s);return"post"===n&&s.push({node:e,path:t}),s}function B(e,n,t){if(0===n.length)return t;const[s,...i]=n,r=e.args.slice();return r[s]=B(r[s],i,t),N(e.op,r)}class D extends Error{constructor(e){super(e),this.name="CasError"}}const C=1e5,P=e=>e<0n?-e:e,R=e=>0n===e?0:P(e).toString(2).length;function U(e,n){for(e=P(e),n=P(n);n;)[e,n]=[n,e%n];return e}class V{constructor(e,n=1n){if(0n===n)throw new D("division by zero");n<0n&&(e=-e,n=-n);const t=U(e,n)||1n;if(this.n=e/t,this.d=n/t,R(this.n)>C||R(this.d)>C)throw new D("a number too large to keep exactly")}static of(e){return new V(BigInt(e))}add(e){return new V(this.n*e.d+e.n*this.d,this.d*e.d)}sub(e){return new V(this.n*e.d-e.n*this.d,this.d*e.d)}mul(e){return new V(this.n*e.n,this.d*e.d)}div(e){if(0n===e.n)throw new D("division by zero");return new V(this.n*e.d,this.d*e.n)}neg(){return new V(-this.n,this.d)}abs(){return this.n<0n?this.neg():this}inv(){return V.ONE.div(this)}pow(e){if((e=BigInt(e))<0n)return this.inv().pow(-e);if((0n===this.n||1n===P(this.n))&&1n===this.d)return 0n===e||-1n===this.n&&e%2n==0n?V.ONE:this;if(BigInt(Math.max(R(this.n),R(this.d)))*e>BigInt(C))throw new D("a power too large to work out exactly");return new V(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 V(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(R(this.n),R(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 L(e){const n=/^(-?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(String(e));if(!n||""===n[2]&&!n[3])return null;const[,t,s,i="",r="0"]=n;let o=new V(BigInt((s||"0")+i),10n**BigInt(i.length));const a=Number(r);return a&&(o=o.mul(V.of(10).pow(a))),t?o.neg():o}function W(e,n){if(e<2n)return e;if(n>=R(e))return 1n;const t=BigInt(n);let s=1n<<BigInt(Math.ceil(R(e)/n));for(;;){const n=((t-1n)*s+e/s**(t-1n))/t;if(n>=s)break;s=n}for(;s**t>e;)s--;for(;(s+1n)**t<=e;)s++;return s}V.ZERO=new V(0n),V.ONE=new V(1n),V.MINUS_ONE=new V(-1n),V.HALF=new V(1n,2n);const _=(()=>{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 H(e,n){const t=BigInt(n);let s=1n,i=1n,r=e;for(const e of _){if(e*e>r)break;if(r%e)continue;let n=0n;for(;r%e===0n;)r/=e,n++;s*=e**(n/t),i*=e**(n%t)}if(r>1n){const e=function(e,n){if(e<0n)return null;if(e<2n)return e;const t=W(e,n);return t**BigInt(n)===e?t:null}(r,n);null!==e?s*=e:i*=r}return{outside:s,inside:i}}const Q=new Set(["pi","e","π"]),J={complex:!1};function Y(e,n){const t=J.complex;J.complex=Boolean(e);try{return n()}finally{J.complex=t}}const K=e=>Q.has(e)||J.complex&&"i"===e,G=e=>J.complex&&"atom"===e.k&&"sym"===e.node.type&&"i"===e.node.token,X=e=>({k:"num",q:e}),ee=X(V.ONE),ne=X(V.ZERO),te=X(V.HALF),se=e=>"num"===e.k,ie=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 ae(e){if("num"===e.k)return 0;if("atom"===e.k)return"sym"===e.node.type&&K(e.node.token)?0:1;if("add"===e.k)return Math.max(...e.terms.map(e=>ae(e.x)));let n=0;for(const t of e.fs){const e=ae(t.b);e&&(n+=e*(se(t.e)?t.e.q.toNumber():1))}return n}function ue(e,n){return"num"===e.k?n&&!se(n)?3:0:G(e)?1.5:"atom"===e.k&&"sym"===e.node.type?K(e.node.token)?n&&!se(n)?3:1:2:"atom"===e.k?3:4}const le=(e,n)=>e<n?-1:e>n?1:0;function ce(e){const n=new Map,t=(e,t)=>{"atom"!==e.k||"sym"!==e.node.type||K(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,se(n.e)?n.e.q.toNumber():1);else t(e,1);return n}function fe(e,n){const t=ae(n.x)-ae(e.x);if(t)return t;const s=ce(e.x),i=ce(n.x);for(const e of[...new Set([...s.keys(),...i.keys()])].sort()){const n=(i.get(e)??0)-(s.get(e)??0);if(n)return n}return le(oe(e.x),oe(n.x))}function pe(e,n){return e.isOne?n:e.isZero?ne:ge([X(e),n])}function he(e){if("num"===e.k)return{coef:e.q,rest:null};if("mul"!==e.k||e.c.isOne)return{coef:V.ONE,rest:e};const n=1===e.fs.length&&se(e.fs[0].e)&&e.fs[0].e.q.isOne?e.fs[0].b:{k:"mul",c:V.ONE,fs:e.fs};return{coef:e.c,rest:n}}function de(e){let n=V.ZERO;const t=new Map,s=(e,n)=>{const s=oe(n),i=t.get(s);i?i.coef=i.coef.add(e):t.set(s,{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)s(e.coef,e.x)}else{const{coef:e,rest:n}=he(t);s(e,n)}const i=[...t.values()].filter(e=>!e.coef.isZero);return i.length?n.isZero&&1===i.length?pe(i[0].coef,i[0].x):(i.sort(fe),{k:"add",c:n,terms:i}):X(n)}function me(e,n){if(!se(n))return e.isOne?{coef:V.ONE,fs:[]}:{coef:V.ONE,fs:[{b:X(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:V.ZERO,fs:[]}}if(e.isOne)return{coef:V.ONE,fs:[]};if(e.sign<0){if(t.d%2n==1n){const{coef:s,fs:i}=me(e.neg(),n);return{coef:t.n%2n==0n?s:s.neg(),fs:i}}if(J.complex&&2n===t.d){const{coef:s,fs:i}=me(e.neg(),n);return{coef:s,fs:[...i,{b:we,e:X(new V(t.n))}]}}return{coef:V.ONE,fs:[{b:X(e),e:n}]}}if(!e.isInteger){const s=me(new V(e.n),n),i=me(new V(e.d),X(t.neg()));return{coef:s.coef.mul(i.coef),fs:[...s.fs,...i.fs]}}const s=t.floor(),i=t.sub(s);if(BigInt(R(e.n))*i.n>BigInt(C)||i.d>1000n)return{coef:V.ONE,fs:[{b:X(e),e:n}]};let r=s.isZero?V.ONE:e.pow(s.n);const{outside:o,inside:a}=H(e.n**i.n,Number(i.d));r=r.mul(new V(o));return{coef:r,fs:a>1n?[{b:X(new V(a)),e:X(new V(1n,i.d))}]:[]}}function ge(e){let n=V.ONE;const t=new Map,s=(e,n)=>{const s=oe(e),i=t.get(s);i?i.e=de([i.e,n]):t.set(s,{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)s(e.b,e.e)}else s(t,ee);if(n.isZero)return ne;const i=[],r=new Map;for(const e of t.values())if(!se(e.e)||!e.e.q.isZero){if("num"===e.b.k){if(se(e.e)&&!e.e.q.isInteger&&e.b.q.sign>0&&e.b.q.isInteger){const n=e.e.q.toString(),t=r.get(n);t?t.n*=e.b.q.n:r.set(n,{n:e.b.q.n,e:e.e});continue}const t=me(e.b.q,e.e);n=n.mul(t.coef),i.push(...t.fs);continue}if("mul"===e.b.k&&se(e.e)&&e.e.q.isInteger){const t=ve(e.b,e.e);"mul"===t.k?(n=n.mul(t.c),i.push(...t.fs)):"num"===t.k?n=n.mul(t.q):i.push({b:t,e:ee});continue}i.push(e)}for(const{n:e,e:t}of r.values()){const s=me(new V(e),t);n=n.mul(s.coef),i.push(...s.fs)}if(n.isZero)return ne;const o=new Map;for(const e of i){const n=oe(e.b),t=o.get(n);t?t.e=de([t.e,e.e]):o.set(n,{...e})}let a=[...o.values()].filter(e=>!(se(e.e)&&e.e.q.isZero));if(J.complex){a=a.flatMap(e=>{if(!G(e.b)||!se(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:ee}]:[]});const e=a.filter(e=>"add"===e.b.k&&se(e.e)&&e.e.q.isInteger&&xe(e.b)),t=a.some(e=>G(e.b)),s=e.every(e=>(e.e.q.sign<0?-e.e.q.n:e.e.q.n)<=60n);if(e.length&&s&&(e.length>1||t||!e[0].e.q.isOne)){const s=a.filter(n=>!e.includes(n)&&!G(n.b));let i=t?[we]:[ee];for(const n of e){const e=n.e.q.sign<0?$e(n.b):n.b;for(let t=0n;t<(n.e.q.sign<0?-n.e.q.n:n.e.q.n);t++)i=qe(i,Ue(e))}return ge([X(n),de(i),...s.map(e=>be(e.b,e.e))])}}if(a.some(e=>"num"===e.b.k&&se(e.e)&&e.e.q.compare(V.ONE)>=0))return ge([X(n),...a.map(e=>"num"===e.b.k?ve(e.b,e.e):{k:"mul",c:V.ONE,fs:[e]})]);if(!a.length)return X(n);if(1===a.length&&!n.isOne&&"add"===a[0].b.k&&se(a[0].e)&&a[0].e.q.isOne){const e=a[0].b;return de([X(n.mul(e.c)),...e.terms.map(e=>pe(n.mul(e.coef),e.x))])}return n.isOne&&1===a.length&&se(a[0].e)&&a[0].e.q.isOne?a[0].b:(a=a.sort((e,n)=>ue(e.b,e.e)-ue(n.b,n.e)||le(oe(e.b),oe(n.b))),{k:"mul",c:n,fs:a})}function ve(e,n){if(J.complex&&se(n)&&n.q.isInteger){if(G(e))return ge([{k:"mul",c:V.ONE,fs:[{b:e,e:n}]}]);if("add"===e.k&&xe(e)&&!n.q.isOne)return ge([{k:"mul",c:V.ONE,fs:[{b:e,e:n}]}])}if(se(n)){if(n.q.isZero){if(se(e)&&e.q.isZero)throw new D("0^0 is undefined");return ee}if(n.q.isOne)return e}if(se(e)){const t=me(e.q,n);if(!t.fs.length)return X(t.coef);if(t.fs.some(e=>G(e.b)))return ge([X(t.coef),...t.fs.map(e=>({k:"mul",c:V.ONE,fs:[e]}))]);const s={k:"mul",c:t.coef,fs:t.fs};return t.coef.isOne&&1===t.fs.length&&se(t.fs[0].e)&&t.fs[0].e.q.isOne?t.fs[0].b:s}if(J.complex&&se(n)&&2n===n.q.d&&xe(e)){const t=ke(e);if(t&&se(t.im)&&!t.im.q.isZero){const e=e=>ve(e,X(V.of(2))),s=ve(de([e(t.re),e(t.im)]),te),i=ve(ge([de([s,t.re]),X(V.HALF)]),te),r=ve(ge([de([s,Ne(t.re)]),X(V.HALF)]),te);return ve(de([i,ge([X(V.of(t.im.q.sign)),r,we])]),X(new V(n.q.n)))}}if("mul"===e.k){if(se(n)&&n.q.isInteger)return ge([X(e.c.pow(n.q.n)),...e.fs.map(e=>be(e.b,ge([e.e,n])))]);if(!e.c.isOne&&e.c.sign>0)return ge([ve(X(e.c),n),ve({k:"mul",c:V.ONE,fs:e.fs},n)]);if(e.c.isOne&&1===e.fs.length){const[t]=e.fs;if(se(t.e)&&se(n)&&1n===t.e.q.n&&t.e.q.d%2n==1n)return be(t.b,ge([t.e,n]))}}return{k:"mul",c:V.ONE,fs:[{b:e,e:n}]}}function be(e,n){return se(n)&&n.q.isZero?ee:se(e)?ve(e,n):se(n)&&n.q.isOne?e:{k:"mul",c:V.ONE,fs:[{b:e,e:n}]}}const we=ie(k("i")),ye=e=>J.complex&&De(e).s.split(" ").includes("i");function xe(e){return J.complex&&ye(e)&&0===Re(De(e)).size}function qe(e,n){const t=[];for(const s of e)for(const e of n)t.push(ge([s,e]));return Ue(de(t))}function ke(e){const n=[],t=[];for(const s of Ue(e)){const{coef:e,rest:i}=he(s),r=i?Ve(i):[],o=r.filter(e=>G(e)),a=r.filter(e=>!G(e));if(a.some(e=>ye(e)))return null;(o.length?t:n).push(ge([X(e),...a]))}return{re:de(n),im:de(t)}}function $e(e){const n=ke(e);if(!n)return ve(e,X(V.MINUS_ONE));const t=de([ve(n.re,X(V.of(2))),ve(n.im,X(V.of(2)))]);return ge([de([n.re,ge([X(V.MINUS_ONE),n.im,we])]),ve(t,X(V.MINUS_ONE))])}const Se={re:([e])=>ke(e)?.re??null,im:([e])=>ke(e)?.im??null,conj:([e])=>{const n=ke(e);return n?de([n.re,ge([X(V.MINUS_ONE),n.im,we])]):null},arg:([e])=>{const n=ke(e);return n?Ee("atan2",[n.im,n.re]):null},abs:([e])=>{const n=ke(e);return!n||se(n.im)&&n.im.q.isZero?null:ve(de([ve(n.re,X(V.of(2))),ve(n.im,X(V.of(2)))]),te)}},Me={Re:"re",re:"re",Im:"im",im:"im",conj:"conj",overline:"conj",bar:"conj",arg:"arg"},Ne=e=>ge([X(V.MINUS_ONE),e]),Oe=(e,n)=>ge([e,ve(n,X(V.MINUS_ONE))]),Ae=3000n,Ie={abs:([e])=>se(e)?X(e.q.abs()):"mul"!==e.k||e.c.isOne?null:ge([X(e.c.abs()),Ee("abs",[he(e).rest])]),floor:([e])=>se(e)?X(e.q.floor()):null,ceil:([e])=>se(e)?X(e.q.ceil()):null,"!":([e])=>{if(!se(e)||!e.q.isInteger||e.q.sign<0||e.q.n>Ae)return null;let n=1n;for(let t=2n;t<=e.q.n;t++)n*=t;return X(new V(n))},mod:([e,n])=>se(e)&&se(n)&&!n.q.isZero?X(e.q.sub(n.q.mul(e.q.div(n.q).floor()))):null,max:e=>e.every(se)&&e.length?e.reduce((e,n)=>n.q.compare(e.q)>0?n:e):null,min:e=>e.every(se)&&e.length?e.reduce((e,n)=>n.q.compare(e.q)<0?n:e):null,gcd:e=>e.length&&e.every(e=>se(e)&&e.q.isInteger)?X(new V(e.reduce((e,n)=>U(e,n.q.n),0n))):null,log:([e,n])=>{if(!se(e)||!se(n)||e.q.sign<=0||n.q.sign<=0||e.q.isOne)return null;if(n.q.isOne)return ne;const t=Math.log(n.q.toNumber())/Math.log(e.q.toNumber());if(!Number.isFinite(t))return null;for(let s=1;s<=12;s++){const i=Math.round(t*s);if(!(Math.abs(t*s-i)>1e-9||0===i)&&(Math.abs(i)<=256&&e.q.pow(BigInt(i)).equals(n.q.pow(BigInt(s)))))return X(new V(BigInt(i),BigInt(s)))}return null},comb:([e,n])=>se(e)&&se(n)&&e.q.isInteger&&n.q.isInteger&&e.q.sign>=0&&n.q.sign>=0&&e.q.n<=Ae?X(function(e,n){if(n>e)return V.ZERO;n>e-n&&(n=e-n);let t=1n;for(let s=1n;s<=n;s++)t=t*(e-n+s)/s;return new V(t)}(e.q.n,n.q.n)):null,perm:([e,n])=>{if(!(se(e)&&se(n)&&e.q.isInteger&&n.q.isInteger&&e.q.sign>=0&&n.q.sign>=0&&e.q.n<=Ae))return null;if(n.q.n>e.q.n)return ne;let t=1n;for(let s=0n;s<n.q.n;s++)t*=e.q.n-s;return X(new V(t))}};function Ee(e,n){if(J.complex&&Se[e]){const t=Se[e](n);if(t)return t}const t=Ie[e];if(t){const e=t(n);if(e)return e}return ie(N(e,n.map(De)))}const Te=new Map;function je(e){const n=J.complex?`ℂ ${e.s}`:e.s,t=Te.get(n);if(t)return t;const s=function(e){if("num"===e.type){const n=L(e.token);if(!n)throw new D(`not an exact number: ${e.token}`);return X(n)}if("sym"===e.type)return"π"===e.token?ie(k("pi")):ie(e);const n=e.args.map(je);switch(e.op){case"+":return de(n);case"-":return((e,n)=>de([e,Ne(n)]))(n[0],n[1]);case"neg":return Ne(n[0]);case"*":return ge(n);case"/":return Oe(n[0],n[1]);case"^":return ve(n[0],n[1]);case"sqrt":return ve(n[0],te);case"root":return ve(n[1],ve(n[0],X(V.MINUS_ONE)));default:{const t=e.op.startsWith("\\:")?e.op.slice(2):null;return t&&J.complex&&Me[t]&&1===n.length?Ee(Me[t],n):t&&d(t)&&h(t).arity===n.length?Ee(t,n):Ee(e.op,n)}}}(e);return Te.size>2e4&&Te.clear(),Te.set(n,s),s}const ze=e=>De(je(e)),Ze=e=>$(String(e));function Fe(e){return e.isInteger?Ze(e.n):N("/",[Ze(e.n),Ze(e.d)])}const Be=new WeakMap;function De(e){let n=Be.get(e);return n||Be.set(e,n=function(e){switch(e.k){case"num":return Fe(e.q);case"atom":return e.node;case"mul":return function(e,n){const t=[],s=[];for(const e of n)se(e.e)&&e.e.q.sign<0?s.push(Ce(e.b,X(e.e.q.neg()))):t.push(Ce(e.b,e.e));let i=1n!==e.n&&-1n!==e.n||!t.length?Pe([Ze(e.n),...t]):Pe(t);-1n===e.n&&t.length&&(i=N("neg",[i]));1n!==e.d&&s.unshift(Ze(e.d));return s.length?N("/",[i,Pe(s)]):i}(e.c,e.fs);case"add":return function(e){let n=null;const t=e=>J.complex&&ye(e.x)&&0===Re(De(e.x)).size,s=[...e.terms.filter(e=>!t(e)),...e.terms.filter(t)],i=e.c,r=()=>{i.isZero||(n=n?i.sign<0?N("-",[n,Fe(i.neg())]):N("+",[n,Fe(i)]):Fe(i))};let o=!1;for(const e of s)!o&&t(e)&&(r(),o=!0),n=n?e.coef.sign<0?N("-",[n,De(pe(e.coef.neg(),e.x))]):N("+",[n,De(pe(e.coef,e.x))]):De(pe(e.coef,e.x));o||r();return n}(e);default:throw new Error(`bad form ${e.k}`)}}(e)),n}function Ce(e,n){const t=De(e);if(se(n)){const e=n.q;if(e.isOne)return t;if(1n===e.n&&2n===e.d)return N("sqrt",[t]);if(1n===e.n)return N("root",[Ze(e.d),t])}return N("^",[t,De(n)])}const Pe=e=>e.reduce((e,n)=>e?N("*",[e,n]):n,null);function Re(e,n=new Set){if("sym"===e.type)K(e.token)||n.add(e.token);else if(A(e))for(const t of e.args)Re(t,n);return n}function Ue(e){if("add"!==e.k)return[e];const n=e.terms.map(e=>pe(e.coef,e.x));return e.c.isZero||n.push(X(e.c)),n}function Ve(e){if("num"===e.k)return[e];if("mul"!==e.k)return[e];const n=e.c.isOne?[]:[X(e.c)];for(const t of e.fs)n.push(be(t.b,t.e));return n}const Le="_",We=new WeakMap;function _e(e,n){return[...n,...h(e.op)?.arity===u?[String(e.args.length)]:[],e.op].join(" ")}function He(e,n){let t=We.get(e);t||We.set(e,t=new Map);const s=t.get(n);if(s)return s;const i=function(e,n){const t={key:Le,slots:[e]};if(e.type!==w||n<=0)return[t];const s=e.args.map(e=>He(e,n-1)),i=[t],r=new Array(s.length).fill(0);for(;;){const n=[],t=[];for(let e=0;e<s.length;e++){const i=s[e][r[e]];n.push(i.key);for(const e of i.slots)t.push(e)}if(i.push({key:_e(e,n),slots:t}),i.length>=4096)break;let o=s.length-1;for(;o>=0&&!(++r[o]<s[o].length);o--)r[o]=0;if(o<0)break}return i}(e,n);return t.set(n,i),i}function Qe(e){return e.type!==w?Le:_e(e,e.args.map(Qe))}function Je(e,n=[]){if(e.type!==w)n.push(e);else for(const t of e.args)Je(t,n);return n}const Ye=new Map,Ke=new Map;class Ge extends Error{constructor(e){super(e),this.name="RequirementError"}}function Xe(e,n,t=""){Ye.set(e,{name:e,fn:n,doc:t,arity:Math.max(0,n.length-1)})}function en(e,n,t=""){Ke.set(e,{name:e,fn:n,doc:t})}function nn(e){return Ye.get(e)||null}function tn(e){return Ke.get(e)||null}const sn=e=>e.type===v;function rn(e,n){return e.type===w&&(e.op===n||e.args.some(e=>rn(e,n)))}Xe("always",()=>!0,"matches anything"),Xe("never",()=>!1,"matches nothing"),Xe("isLeaf",e=>e.type!==w,"a bare operand, not an operation"),Xe("isCompound",e=>e.type===w,"an operation, not a bare operand"),Xe("isSymbol",e=>e.type===b,"a non-numeric operand such as x"),Xe("isOperation",(e,n)=>e.type===w&&e.op===n,"is this specific operation"),Xe("notOperation",(e,n)=>!(e.type===w&&e.op===n),"is anything except this operation"),Xe("isNumber",sn,"a numeric literal"),Xe("isInteger",e=>sn(e)&&Number.isInteger(e.value),"a whole number"),Xe("isPositive",e=>sn(e)&&e.value>0,"greater than zero"),Xe("isNegative",e=>sn(e)&&e.value<0,"less than zero"),Xe("isNonNegative",e=>sn(e)&&e.value>=0,"zero or greater"),Xe("isZero",e=>sn(e)&&0===e.value,"exactly 0"),Xe("isOne",e=>sn(e)&&1===e.value,"exactly 1"),Xe("isNonZero",e=>sn(e)&&0!==e.value,"a number that is provably not 0"),Xe("isNotZeroLiteral",e=>!(sn(e)&&0===e.value),"anything except a literal 0"),Xe("isPositiveInteger",e=>sn(e)&&Number.isInteger(e.value)&&e.value>0,"a whole number above 0"),Xe("isNegativeInteger",e=>sn(e)&&Number.isInteger(e.value)&&e.value<0,"a whole number below 0"),Xe("isEven",e=>sn(e)&&Number.isInteger(e.value)&&e.value%2==0,"a whole even number"),Xe("isOdd",e=>sn(e)&&Number.isInteger(e.value)&&1===Math.abs(e.value%2),"a whole odd number"),Xe("greaterThan",(e,n)=>sn(e)&&e.value>Number(n),"above a given value"),Xe("lessThan",(e,n)=>sn(e)&&e.value<Number(n),"below a given value"),Xe("isValue",(e,n)=>sn(e)&&e.value===Number(n),"equals a given number"),Xe("isNumeric",Z,"contains no symbols: a constant (it need not fold to a number: 1 sin)"),Xe("hasSymbol",e=>!Z(e),"mentions a symbol somewhere, so it is not just a number"),Xe("isVar",(e,n)=>e.type===b&&e.token===String(n),"is exactly this symbol"),Xe("contains",(e,n)=>z(e).includes(String(n)),"mentions this operand somewhere"),Xe("isFree",(e,n)=>!z(e).includes(String(n)),"never mentions this operand"),Xe("hasOperation",(e,n)=>rn(e,String(n)),"uses this operation somewhere inside"),Xe("equals",(e,n)=>e.s===String(n),"is exactly this postfix expression");const on=e=>e.type===w?null:e.token;function an(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 Ge(`bad requirement: ${JSON.stringify(e)}`)}en("freeOf",(e,n)=>{const t=on(n);return null!==t&&!z(e).includes(t)},"the first operand never mentions the second"),en("dependsOn",(e,n)=>{const t=on(n);return null!==t&&z(e).includes(t)},"the first operand does mention the second"),en("sameAs",(...e)=>e.every(n=>n.s===e[0].s),"these operands are structurally identical"),en("differs",(...e)=>new Set(e.map(e=>e.s)).size===e.length,"these operands are all different"),en("sameValue",(...e)=>e.every(e=>sn(e))&&e.every(n=>n.value===e[0].value),"these operands are the same number");const un="simplify";class ln extends Error{constructor(e,n){super(n?`rule "${n}": ${e}`:e),this.name="RuleError",this.ruleId=n}}const cn=/^[A-Za-z_][A-Za-z0-9_]*$/;function fn(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 ln('"=" needs an operand after it',n);return{token:e}}if(!cn.test(t))throw new ln(`"${t}" is not a usable slot name; use letters, digits and _`,n);if(d(t))throw new ln(`slot name "${t}" collides with an operator`,n);return{name:t}}function pn(e){if(!A(e))return[e];const n=e.args.map(pn),t=h(e.op),s=[];for(const i of function(e){let n=[[]];for(const t of e){const e=[];for(const s of n)for(const n of t)e.push(s.concat([n]));if(n=e,n.length>64)return n.slice(0,64)}return n}(n))if(s.push(N(e.op,i)),t.commutative&&2===i.length&&i[0].s!==i[1].s&&s.push(N(e.op,[i[1],i[0]])),s.length>=64)break;return s}function hn(e,n=[]){return"op"===e.kind?e.args.forEach(e=>hn(e,n)):"const"===e.kind&&e.free&&n.push(e.node.token),n}function dn(e){if(!e||"object"!=typeof e)throw new ln("rule must be a mapping");const n=e.id||e.name;if(!n)throw new ln("rule needs an id");if(!e.pattern)throw new ln("rule needs a pattern",n);if(void 0===e.output||null===e.output)throw new ln("rule needs an output",n);let t;try{t=I(String(e.pattern))}catch(e){if(e instanceof x)throw new ln(`bad pattern: ${e.message}`,n);throw e}const s=Je(t).map(e=>fn(e,n)),i=new Set(s.filter(e=>e.name).map(e=>e.name)),r=function(e,n,t){const s=[],i=e.when||{};if("object"!=typeof i||Array.isArray(i))throw new ln('"when" must map slot names to lists of requirements',t);for(const[e,r]of Object.entries(i)){if(!n.has(e))throw new ln(`"when" mentions "${e}", which is not a slot in the pattern`,t);const i=Array.isArray(r)?r:[r];for(const n of i){const{name:i,args:r}=an(n),o=nn(i);if(!o)throw new ln(`unknown requirement "${i}"`,t);s.push({slot:e,name:i,args:r,fn:o.fn})}}return s}(e,i,n),o=function(e,n,t){const s=[],i=e.require||[];if(!Array.isArray(i))throw new ln('"require" must be a list of relations',t);for(const e of i){const{name:i,args:r}=an(e),o=tn(i);if(!o)throw new ln(`unknown relation "${i}"`,t);if(r.length<2)throw new ln(`relation "${i}" needs at least two operands`,t);for(const e of r)if("string"==typeof e&&!n.has(e)&&cn.test(e))throw new ln(`relation "${i}" mentions "${e}", which is not a slot in the pattern`,t);s.push({name:i,args:r,fn:o.fn})}return s}(e,i,n),a=function(e,n,t){let s;try{s=I(e)}catch(n){throw new ln(`bad output "${e}": ${n.message}`,t)}const i=e=>A(e)?{kind:"op",op:e.op,args:e.args.map(i)}:O(e)?{kind:"const",node:e}:n.has(e.token)?{kind:"slot",name:e.token}:e.token.startsWith("=")?{kind:"const",node:k(e.token.slice(1))}:{kind:"const",node:e,free:!0};return i(s)}(String(e.output),i,n),u=e.commutative?pn(t):[t],l=[],c=new Set;for(const e of u){const t=Qe(e),s=Je(e).map(e=>fn(e,n)),i=t+"\0"+s.map(e=>e.name??(void 0!==e.literal?`#${e.literal}`:`=${e.token}`)).join(",");c.has(i)||(c.add(i),l.push({key:t,slots:s}))}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):un,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:r,require:o,slots:[...i],depth:T(t),bindings:l,freeSymbols:hn(a),source:e};for(const e of l)e.rule=f;return f}function mn(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!==un&&(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 gn extends Error{constructor(e,n){super(null==n?e:`${e} (line ${n+1})`),this.name="YamlError",this.line=n}}class vn{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 bn=e=>"-"===e||e.startsWith("- ");function wn(e){let n=null,t=0;for(let s=0;s<e.length;s++){const i=e[s];if(n)i===n?"'"===n&&"'"===e[s+1]?s++:n=null:'"'===n&&"\\"===i&&s++;else if('"'===i||"'"===i)n=i;else if("["===i||"{"===i)t++;else if("]"===i||"}"===i)t--;else if(":"===i&&0===t&&(s+1===e.length||" "===e[s+1])){const n=e.slice(0,s).trim();return""===n?null:{key:yn(n),rest:e.slice(s+1).trim()}}}return null}function yn(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 xn(e){const n=new vn(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 s=function(e){let n=null;for(let t=0;t<e.length;t++){const s=e[t];if(n)s===n?"'"===n&&"'"===e[t+1]?t++:n=null:'"'===n&&"\\"===s&&t++;else if('"'===s||"'"===s)n=s;else if("#"===s&&(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:s,blank:""===s}})}(e));let t=n.peek();if(t&&"---"===t.text&&(n.next(),t=n.peek()),!t)return null;const s=kn(n,t.indent),i=n.peek();if(i&&"..."!==i.text&&"---"!==i.text)throw new gn(`unexpected content "${i.text}"`,i.n);return s}const qn=/^[|>][-+]?\d*$/;function kn(e,n){const t=e.peek();return!t||t.indent<n?null:bn(t.text)?$n(e,t.indent):wn(t.text)?function(e,n){const t={};for(;;){const s=e.peek();if(!s||s.indent!==n)break;const i=wn(s.text);if(!i)break;e.next();const{key:r,rest:o}=i;if(""===o){const s=e.peek();s&&s.indent>n?t[r]=kn(e,s.indent):s&&s.indent===n&&bn(s.text)?t[r]=$n(e,n):t[r]=null}else qn.test(o)?t[r]=Sn(e,o,n):t[r]=Mn(o,s.n)}return t}(e,t.indent):(e.next(),qn.test(t.text)?Sn(e,t.text,t.indent-1):Mn(t.text,t.n))}function $n(e,n){const t=[];for(;;){const s=e.peek();if(!s||s.indent!==n||!bn(s.text))break;if(e.next(),"-"===s.text){const s=e.peek();t.push(s&&s.indent>n?kn(e,s.indent):null);continue}if(qn.test(s.text.slice(2).trim())){t.push(Sn(e,s.text.slice(2).trim(),n));continue}const i=s.text.slice(2),r=n+2+(i.length-i.trimStart().length);e.push({raw:s.raw,n:s.n,indent:r,text:i.trim(),blank:!1}),t.push(kn(e,r))}return t}function Sn(e,n,t){const s=n[0],i=(n.match(/[-+]/)||[""])[0],r=(n.match(/\d+/)||[null])[0];let o=r?t+Number(r):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 s=n.raw.search(/\S/);if(s<=t)break;if(null===o&&(o=s),s<o)break;a.push(n.raw.slice(o)),e.i++}for(;a.length&&""===a[a.length-1];)a.pop();let u;if("|"===s)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"-"===i?u:"+"===i?u+"\n":""===u?"":u+"\n"}function Mn(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},s=On(t);if(Nn(t),t.i<t.text.length)throw new gn(`unexpected "${t.text.slice(t.i)}" in flow value`,n);return s}(t,n):'"'===t[0]||"'"===t[0]?yn(t):/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(t)?Number(t):t)}const Nn=e=>{for(;e.i<e.text.length&&/\s/.test(e.text[e.i]);)e.i++};function On(e){Nn(e);const n=e.text[e.i];return"["===n?function(e){e.i++;const n=[];for(;;){if(Nn(e),e.i>=e.text.length)throw new gn("unterminated [",e.line);if("]"===e.text[e.i])return e.i++,n;if(n.push(On(e)),Nn(e),","===e.text[e.i])e.i++;else if("]"!==e.text[e.i])throw new gn(`expected , or ] near "${e.text.slice(e.i)}"`,e.line)}}(e):"{"===n?function(e){e.i++;const n={};for(;;){if(Nn(e),e.i>=e.text.length)throw new gn("unterminated {",e.line);if("}"===e.text[e.i])return e.i++,n;const t=String(On(e));if(Nn(e),":"!==e.text[e.i])throw new gn(`expected : after "${t}"`,e.line);if(e.i++,n[t]=On(e),Nn(e),","===e.text[e.i])e.i++;else if("}"!==e.text[e.i])throw new gn(`expected , or } near "${e.text.slice(e.i)}"`,e.line)}}(e):Mn(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 gn("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 An=/^(true|false|null|yes|no|on|off|~)$/i;function In(e){if(null==e)return"null";if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e))throw new gn(`cannot serialize ${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)||An.test(e)||/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(e))}(n)?JSON.stringify(n):n}const En=e=>null==e||"object"!=typeof e;function Tn(e){return Array.isArray(e)?`[${e.map(Tn).join(", ")}]`:e&&"object"==typeof e?`{${Object.entries(e).map(([e,n])=>`${In(e)}: ${Tn(n)}`).join(", ")}}`:In(e)}function jn(e){return Array.isArray(e)?!!e.every(e=>En(e)||Array.isArray(e)&&e.every(En))&&Tn(e).length<=72:!(!e||"object"!=typeof e)&&(Object.values(e).every(e=>En(e)||Array.isArray(e)&&e.every(En))&&Tn(e).length<=72)}function zn(e){const n=[];return Zn(e,0,n),n.length?n.join("\n")+"\n":""}function Zn(e,n,t){const s=" ".repeat(n);if(Array.isArray(e)){if(0===e.length)return void t.push(s+"[]");for(const s of e)Fn(s,n,t)}else{if(e&&"object"==typeof e){const i=Object.entries(e).filter(([,e])=>void 0!==e);if(0===i.length)return void t.push(s+"{}");for(const[e,s]of i)Bn(e,s,n,t);return}!function(e,n,t){if("string"==typeof e&&e.includes("\n")){t.push(n+"|-");for(const s of e.replace(/\n+$/,"").split("\n"))t.push(n+" "+s);return}t.push(n+In(e))}(e,s,t)}}function Fn(e,n,t){const s=" ".repeat(n);if(null!==e&&"object"==typeof e&&!jn(e)){const i=[];if(Zn(e,n+2,i),0===i.length)return void t.push(s+"-");t.push(s+"- "+i[0].slice(n+2));for(let e=1;e<i.length;e++)t.push(i[e]);return}if(null===e||"object"!=typeof e)if("string"==typeof e&&e.includes("\n")){t.push(s+"- |-");for(const s of e.replace(/\n+$/,"").split("\n"))t.push(" ".repeat(n+4)+s)}else t.push(s+"- "+In(e));else t.push(s+"- "+Tn(e))}function Bn(e,n,t,s){const i=" ".repeat(t),r=In(e);if("string"==typeof n&&n.includes("\n")){s.push(`${i}${r}: |-`);for(const e of n.replace(/\n+$/,"").split("\n"))s.push(" ".repeat(t+2)+e)}else{if(null!==n&&"object"==typeof n)return jn(n)?void s.push(`${i}${r}: ${Tn(n)}`):(s.push(`${i}${r}:`),void Zn(n,Array.isArray(n)?t:t+2,s));s.push(`${i}${r}: ${In(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:dn(e);if(this.rules.some(e=>e.id===n.id))throw new ln(`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===un?-1:n===un?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=xn(e);return Dn.fromSpecs(t,{strict:n})}static fromSpecs(e,{strict:n=!0}={}){let t=e,s="";if(e&&!Array.isArray(e)&&"object"==typeof e&&(t=e.rules,s=e.name?String(e.name):""),!Array.isArray(t))throw new ln('expected a list of rules, or a mapping with a "rules" list');const i=new Dn;i.name=s;const r=[];for(let e=0;e<t.length;e++)try{i.add(t[e])}catch(n){r.push(`#${e+1}: ${n.message}`)}if(r.length&&n)throw new ln(`${r.length} rule(s) failed to compile:\n ${r.join("\n ")}`);return i.errors=r,i}toSpecs(){return this.rules.map(mn)}toYaml(){const e=this.toSpecs();return this.name?zn({name:this.name,rules:e}):zn(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 Cn(e,n){const t=Object.create(null),s=e.slots;for(let e=0;e<s.length;e++){const i=s[e],r=n[e];if(void 0!==i.literal){if(!O(r)||r.value!==i.literal)return null;continue}if(void 0!==i.token){if(r.s!==i.token)return null;continue}const o=t[i.name];if(void 0!==o){if(o.s!==r.s)return null}else t[i.name]=r}return t}function Pn(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 Rn(e,n){return n.rule.priority-e.rule.priority||n.rule.depth-e.rule.depth}function Un(e,n){const t=[];if(0===n.maxDepth)return t;for(const{key:s,slots:i}of function(e,n){const t=He(e,n),s=[];for(const e of t)e.key!==Le&&s.push(e);return s}(e,n.maxDepth)){const e=n.candidates(s);if(e)for(const n of e){const e=Cn(n,i);e&&(Pn(n.rule,e)&&t.push({rule:n.rule,binding:n,key:s,bound:e}))}}return t.sort(Rn)}function Vn(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 N(e.op,e.args.map(e=>Vn(e,n)));default:throw new Error(`bad output template: ${JSON.stringify(e)}`)}}const Ln=4e5,Wn=()=>new D("a number too large to approximate"),_n=e=>e<0n?-e:e;class Hn{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 W(e*this.S,2)}series(e,n){let t=0n,s=e;for(let e=1;0n!==s;e++)if(t+=s,s=n(s,e),e>1e5)throw new D("a series did not converge");return t}atanhInv(e){const n=BigInt(e),t=n*n;let s=this.S/n,i=0n;for(let e=1n;0n!==s;e+=2n)i+=s/e,s/=t;return i}atanInv(e){const n=BigInt(e),t=n*n;let s=this.S/n,i=0n;for(let e=1n,n=1n;0n!==s;e+=2n,n=-n)i+=n*s/e,s/=t;return i}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(Ln))throw Wn();if(n<-BigInt(Ln))return 0n;const t=e-n*this.ln2,s=this.series(this.S,(e,n)=>e*t/this.S/BigInt(n));return n>=0n?s<<n:s>>-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 s=this.div(t-this.S,t+this.S),i=this.mul(s,s);let r=s,o=0n;for(let e=1n;0n!==r;e+=2n)o+=r/e,r=this.mul(r,i);return 2n*o+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 s=this.mul(t,t);return this.series(t,(e,n)=>-e*s/this.S/BigInt(2*n*(2*n+1)))}cos(e){return this.sin(e+this.pi/2n)}atan(e){if(_n(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 s=n,i=0n;for(let e=1n,n=1n;0n!==s;e+=2n,n=-n)i+=n*s/e,s=this.mul(s,t);return 4n*i}asin(e){if(_n(e)>this.S)throw new D("arcsin of a number beyond ±1 is not real");return _n(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 Qn(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 Jn={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 s=e.mul(t[0],t[0])+e.mul(t[1],t[1]);if(0n===s)throw new D("division by zero");return[e.div(e.mul(n[0],t[0])+e.mul(n[1],t[1]),s),e.div(e.mul(n[1],t[0])-e.mul(n[0],t[1]),s)]},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=Jn.abs(e,n);if(0n===t)throw new D("the log of 0 is undefined");return[e.ln(t),Qn(e,n[1],n[0])]},pow(e,n,t,s){if(0n===n[0]&&0n===n[1])return[0n,0n];if(s&&s.isInteger){let t=s.n<0n?-s.n:s.n,i=[e.S,0n],r=n;for(;t>0n;)1n&t&&(i=Jn.mul(e,i,r)),r=Jn.mul(e,r,r),t>>=1n;return s.n<0n?Jn.div(e,[e.S,0n],i):i}return Jn.exp(e,Jn.mul(e,t,Jn.ln(e,n)))},sinh:(e,n)=>(e.exp(n)-e.exp(-n))/2n,cosh:(e,n)=>(e.exp(n)+e.exp(-n))/2n},Yn={sin:(e,[n,t])=>[e.mul(e.sin(n),Jn.cosh(e,t)),e.mul(e.cos(n),Jn.sinh(e,t))],cos:(e,[n,t])=>[e.mul(e.cos(n),Jn.cosh(e,t)),-e.mul(e.sin(n),Jn.sinh(e,t))],tan:(e,n)=>Jn.div(e,Yn.sin(e,n),Yn.cos(e,n)),ln:(e,n)=>Jn.ln(e,n),sqrt:(e,n)=>Jn.exp(e,Jn.mul(e,[e.S/2n,0n],Jn.ln(e,n))),sinh:(e,[n,t])=>[e.mul(Jn.sinh(e,n),e.cos(t)),e.mul(Jn.cosh(e,n),e.sin(t))],cosh:(e,[n,t])=>[e.mul(Jn.cosh(e,n),e.cos(t)),e.mul(Jn.sinh(e,n),e.sin(t))]},Kn=e=>({q:e}),Gn=([e,n])=>0n===n?{f:e}:{z:[e,n]};function Xn(e,n,t){const s=e=>((e,n)=>n.z??[et(e,n),0n])(t,n[e]);switch(e.op){case"+":return Gn(Jn.add(s(0),s(1)));case"-":return Gn(Jn.sub(s(0),s(1)));case"neg":return Gn([-s(0)[0],-s(0)[1]]);case"*":return Gn(Jn.mul(t,s(0),s(1)));case"/":return Gn(Jn.div(t,s(0),s(1)));case"^":return Gn(Jn.pow(t,s(0),s(1),n[1].q));case"sqrt":return Gn(Yn.sqrt(t,s(0)));case"root":return Gn(Jn.pow(t,s(1),Jn.div(t,[t.S,0n],s(0)),n[0].q?.inv()));case"abs":return{f:Jn.abs(t,s(0))};case"arg":return{f:Qn(t,s(0)[1],s(0)[0])};case"re":return{f:s(0)[0]};case"im":return{f:s(0)[1]};case"conj":return Gn([s(0)[0],-s(0)[1]]);case"log":return Gn(Jn.div(t,Jn.ln(t,s(1)),Jn.ln(t,s(0))));default:{const i=Yn[e.op];if(!i||1!==n.length)throw new D(`no complex value for ${e.op}`);return Gn(i(t,s(0)))}}}function et(e,n){return n.q?e.fromQ(n.q):n.f}const nt={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),arcsec:(e,n)=>{if(_n(n)<e.S)throw new D("arcsec of a number between -1 and 1 is not real");return e.pi/2n-e.asin(e.div(e.S,n))},arccsc:(e,n)=>{if(_n(n)<e.S)throw new D("arccsc of a number between -1 and 1 is not real");return e.asin(e.div(e.S,n))},arccot:(e,n)=>e.pi/2n-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),s=e.exp(-n);return e.div(t-s,t+s)},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(_n(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 tt(e,n,t){if("num"===e.type)return Kn(L(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&&J.complex)return{z:[0n,n.S]};if(t&&e.token in t){const n=t[e.token],s="number"==typeof n||"string"==typeof n||"bigint"==typeof n?L(String(n)):null;if(!s)throw new D(`the value of ${e.token} is not a number`);return Kn(s)}throw new D(`${e.token} has no value`)}J.complex&&e.op.startsWith("\\:")&&Me[e.op.slice(2)]&&(e=N(Me[e.op.slice(2)],e.args));const s=e.args.map(e=>tt(e,n,t));if(s.some(e=>e.z)||["re","im","conj","arg"].includes(e.op)||function(e,n){if(!J.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,s))return Xn(e,s,n);const i=s.every(e=>e.q),r=e=>et(n,s[e]);switch(e.op){case"+":return i?Kn(s[0].q.add(s[1].q)):{f:r(0)+r(1)};case"-":return i?Kn(s[0].q.sub(s[1].q)):{f:r(0)-r(1)};case"neg":return s[0].q?Kn(s[0].q.neg()):{f:-s[0].f};case"*":return i?Kn(s[0].q.mul(s[1].q)):{f:n.mul(r(0),r(1))};case"/":return i?Kn(s[0].q.div(s[1].q)):{f:n.div(r(0),r(1))};case"^":return it(n,s[0],s[1]);case"sqrt":return it(n,s[0],Kn(V.HALF));case"root":return it(n,s[1],s[0].q?Kn(s[0].q.inv()):{f:n.div(n.S,s[0].f)});case"abs":return s[0].q?Kn(s[0].q.abs()):{f:_n(s[0].f)};case"floor":return Kn(s[0].q?s[0].q.floor():new V(st(s[0].f,n.S)));case"ceil":return Kn(s[0].q?s[0].q.ceil():new V(-st(-s[0].f,n.S)));case"log":return{f:n.div(n.ln(r(1)),n.ln(r(0)))};case"atan2":return{f:Qn(n,r(0),r(1))};case"max":case"min":if(!s.length)throw new D(`${e.op} of nothing`);return i?Kn(s.map(e=>e.q).reduce((n,t)=>("max"===e.op?t.sub(n).sign>0:t.sub(n).sign<0)?t:n)):{f:s.map((e,n)=>r(n)).reduce((n,t)=>"max"===e.op?t>n?t:n:t<n?t:n)};case"sum":return i?Kn(s.reduce((e,n)=>e.add(n.q),V.ZERO)):{f:s.reduce((e,n,t)=>e+r(t),0n)};case"prod":return i?Kn(s.reduce((e,n)=>e.mul(n.q),V.ONE)):{f:s.reduce((e,t,s)=>n.mul(e,r(s)),n.S)};case"mean":if(!s.length)throw new D("mean of nothing");return i?Kn(s.reduce((e,n)=>e.add(n.q),V.ZERO).div(new V(BigInt(s.length)))):{f:s.reduce((e,n,t)=>e+r(t),0n)/BigInt(s.length)};case"mod":{if(i){if(s[1].q.isZero)throw new D("mod 0 is undefined");return Kn(s[0].q.sub(s[1].q.mul(s[0].q.div(s[1].q).floor())))}const e=r(1);if(0n===e)throw new D("mod 0 is undefined");return{f:r(0)-n.mul(e,st(n.div(r(0),e),n.S)*n.S)}}case"round":{if(!s[1].q?.isInteger)throw new D("round needs a whole number of places");const e=10n**_n(s[1].q.n),t=s[0].q??new V(r(0),n.S),i=s[1].q.sign>=0,o=(i?t.mul(new V(e)):t.div(new V(e))).add(V.HALF).floor();return Kn(i?o.div(new V(e)):o.mul(new V(e)))}case"!":{if(!s[0].q?.isInteger||s[0].q.sign<0)throw new D("factorial is only worked out for whole numbers");let e=1n;for(let n=2n;n<=s[0].q.n;n++)if(e*=n,0n==(255n&n)&&R(e)>Ln)throw Wn();return Kn(new V(e))}default:{const t=nt[e.op];if(!t||1!==s.length)throw new D(`no numeric value for ${e.op}`);return{f:t(n,r(0))}}}}const st=(e,n)=>{const t=e/n;return e<0n&&t*n!==e?t-1n:t};function it(e,n,t){if(t.q&&t.q.isInteger){if(n.q)return Kn(n.q.pow(t.q.n));let s=t.q.n;const i=s<0n;i&&(s=-s);let r=e.S,o=n.f;for(;s>0n;){if(1n&s&&(r=e.mul(r,o)),o=e.mul(o,o),R(r)>Ln+4*e.P||R(o)>8e5){if(i)return{f:0n};throw Wn()}s>>=1n}return{f:i?e.div(e.S,r):r}}const s=et(e,n);if(0n===s){if(t.q?t.q.sign>0:t.f>0n)return Kn(V.ZERO);throw new D("0 to a power that is not positive is undefined")}if(s<0n){if(t.q&&t.q.d%2n==1n){const n=it(e,{f:-s},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===_n(t.q.n)&&t.q.d<=64n){const n=W(s*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(et(e,t),e.ln(s)))}}function rt(e,n,t){const s=e<0n?"-":"",i=_n(e);if(0n===i)return{sign:"",digits:"0",point:1};const r=i.toString(),o=r.length-n.P;let a=r.slice(0,t);r.length>t&&r[t]>="5"&&(a=(BigInt(a)+1n).toString());let u=o;return a.length>t&&(a=a.slice(0,t),u++),{sign:s,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 at(e){let n=0n,t=0n,s=e.d;for(;s%2n==0n;)s/=2n,n++;for(;s%5n==0n;)s/=5n,t++;const i=n>t?n:t;let r=_n(e.n)*10n**i/e.d;if(0n===r)return 1;for(;r%10n==0n;)r/=10n;return r.toString().length}function ut(e){let n=e.d;for(;n%2n==0n;)n/=2n;for(;n%5n==0n;)n/=5n;return 1n===n}function lt(e){const n=/^(-?[\d.]+)e(-?\d+)$/.exec(e);return n?N("*",[$(n[1]),N("^",[$("10"),$(n[2])])]):$(e)}function ct(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 s=n+25,i=null;for(let r=0;r<4;r++){const o=new Hn(s),a=tt(e,o,t);if(a.z){const e=pt(a.z,o,n);if(e.retry&&r<3){s+=e.retry;continue}return void 0===e.real?e:ft(e.real,o,n,null)}if(a.q&&a.q.isInteger&&_n(a.q.n).toString().length<=n)return{text:a.q.n.toString(),node:$(a.q.n.toString()),number:Number(a.q.n),re:Number(a.q.n),im:0,exact:!0};const u=et(o,a);if(0n===u&&(!a.q||!a.q.isZero)&&r<3){i=null,s*=4;continue}const l=rt(u,o,n);if(i&&l.point<-10&&i.point-l.point>=(s-i.P)/2)return{text:"0",node:$("0"),number:0,re:0,im:0,exact:!1};if(!(l.point<-10&&r<3)||i&&i.point===l.point)return ft(u,o,n,a.q);i={point:l.point,P:s},s+=10-l.point}throw new D("could not approximate")}function ft(e,n,t,s){const i=ot(rt(e,n,t));return{text:i,node:lt(i),number:Number(i),re:Number(i),im:0,exact:Boolean(s)&&ut(s)&&at(s)<=t}}function pt([e,n],t,s){const i=10n**BigInt(Math.max(0,t.P-s-12)),r=e=>_n(e)>i;if(!r(n))return{real:e};const o=rt(n,t,s);if(o.point<-10&&r(n))return{retry:10-o.point};const a=ot(o),u="1"===a?"i":"-1"===a?"-i":`${a}i`,l="1"===a?k("i"):N("*",[lt(a.replace(/^-/,"")),k("i")]);if(!r(e))return{text:u,node:a.startsWith("-")?N("neg",[l]):l,number:NaN,re:0,im:Number(a),exact:!1};const c=ot(rt(e,t,s)),f=a.startsWith("-"),p="1"===a.replace(/^-/,"")?k("i"):N("*",[lt(a.replace(/^-/,"")),k("i")]);return{text:`${c} ${f?"-":"+"} ${u.replace(/^-/,"")}`,node:N(f?"-":"+",[lt(c),p]),number:NaN,re:Number(c),im:Number(a),exact:!1}}function ht(e,n={}){const t=e=>(e=>0===Re(e).size)(e)?"num"===e.type&&/^-?\d+$/.test(e.token)?e:ct(e,n).node:A(e)?N(e.op,e.args.map(t)):e;return t(e)}const dt={variable:null},mt=(e,n)=>null!==n&&Re(e).has(n);function gt(e){if("num"===e.type)return L(e.token);if(A(e)&&"/"===e.op&&e.args.every(e=>"num"===e.type)){const n=L(e.args[0].token),t=L(e.args[1].token);return n&&t&&!t.isZero?n.div(t):null}return null}const vt=e=>0===Re(e).size;function bt(e,n,t){const s=function(e){const n=je(e);return"num"===n.k?n.q.isZero?n.q:null:"atom"===n.k&&"sym"===n.node.type&&"pi"===n.node.token?L("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(!s)return!1;const[i,r="1"]=String(n).split("/");return t(s.compare(L(i).div(L(r))))}function wt(e){if(!vt(e))return NaN;try{const{number:n}=ct(e,{digits:30});return Math.sign(n)}catch{return NaN}}function yt(){nn("hasVariable")||(Xe("hasVariable",e=>mt(e,dt.variable),"mentions the variable being solved for"),Xe("freeOfVariable",e=>null!==dt.variable&&!mt(e,dt.variable),"does not mention the variable being solved for"),Xe("isRational",e=>null!==gt(e),"an exact number: 3, -2, 1/2"),Xe("isWhole",e=>gt(e)?.isInteger??!1,"a whole number (any size)"),Xe("isEvenWhole",e=>{const n=gt(e);return Boolean(n?.isInteger&&n.n%2n==0n)},"an even whole number"),Xe("isOddWhole",e=>{const n=gt(e);return Boolean(n?.isInteger&&n.n%2n!=0n)},"an odd whole number"),Xe("isPositiveRational",e=>(gt(e)?.sign??0)>0,"an exact number above 0"),Xe("isNegativeRational",e=>(gt(e)?.sign??0)<0,"an exact number below 0"),Xe("isConstant",vt,"has no unknowns (numbers, π and e only)"),Xe("notOne",e=>{const n=gt(e);return!n||!n.isOne},"anything except the number 1"),Xe("notMinusOne",e=>{const n=gt(e);return!n||!n.equals(L("-1"))},"anything except the number -1"),Xe("hasMinusSign",e=>function(e){const n=je(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"),Xe("piMultipleAtLeast",(e,n)=>bt(e,n,e=>e>=0),"a multiple of π, at least k·π"),Xe("piMultipleAbove",(e,n)=>bt(e,n,e=>e>0),"a multiple of π, above k·π"),Xe("piMultipleBelow",(e,n)=>bt(e,n,e=>e<0),"a multiple of π, below k·π"),Xe("piMultipleAtMost",(e,n)=>bt(e,n,e=>e<=0),"a multiple of π, at most k·π"),Xe("isPositiveConstant",e=>wt(e)>0,"no unknowns, and above 0 (e, π, √2, 3)"),Xe("isNegativeConstant",e=>wt(e)<0,"no unknowns, and below 0"),Xe("hasImaginaryPart",e=>{if(!J.complex)return!1;const n=ke(je(e));return Boolean(n)&&!("num"===n.im.k&&n.im.q.isZero)},"complex mode: has a nonzero imaginary part (unknowns count as real)"),Xe("isSymbolNode",e=>"sym"===e.type&&!Q.has(e.token),"a single unknown such as x"))}function xt(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=I(e),t=e=>"num"===e.type||("sym"===e.type?e.token.startsWith("="):e.args.every(t)),s=e=>"sym"===e.type?k(e.token.slice(1)):"num"===e.type?e:N(e.op,e.args.map(s)),i=e=>"sym"===e.type?k(`=${e.token}`):"num"===e.type?e:N(e.op,e.args.map(i)),r=e=>"op"!==e.type?e:t(e)?i(ze(s(e))):N(e.op,e.args.map(r));return r(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 qt(e,n,t,s){return e.explain?e.explain.replace(/\{(\w+)\}/g,(e,i)=>"result"===i?t?s(t):e:n[i]?s(n[i]):e).trim():""}const kt=e=>A(e)&&("+"===e.op||"-"===e.op),$t=e=>A(e)&&("*"===e.op||"/"===e.op);function*St(e,n,{order:t="pre"}={}){for(const s of function(e,n,{order:t="post"}={}){const s=[];for(const{node:i,path:r}of F(e,t))for(const e of Un(i,n))s.push({...e,node:i,path:r});return s}(e,n,{order:t})){const n=Vn(s.rule.outputTemplate,s.bound);yield{rule:s.rule,bound:s.bound,path:s.path,before:s.node,after:n,next:()=>ze(B(e,s.path,n))}}for(const{node:s,path:i}of F(e,t)){const t=kt(s);if(!t&&!$t(s))continue;const r=t?Ue(je(s)):Ve(je(s));if(r.length<3)continue;const o=t?de:ge;for(let t=0;t<r.length;t++)for(let s=t+1;s<r.length;s++){const a=De(o([r[t],r[s]]));for(const u of Un(a,n)){const n=Vn(u.rule.outputTemplate,u.bound),l=r.filter((e,n)=>n!==t&&n!==s);yield{rule:u.rule,bound:u.bound,path:i,before:a,after:n,next:()=>ze(B(e,i,De(o([je(n),...l]))))}}}}}function Mt(e,n,{format:t,order:s="pre",maxSteps:i=200,variable:r=null}={}){const o=dt.variable;dt.variable=r;try{let r=ze(e);const o=new Set([r.s]),a=[];for(let e=0;e<i;e++){let e=null;for(const t of St(r,n,{order:s})){const n=t.next();if(n.s!==r.s&&!o.has(n.s)){e={c:t,next:n};break}}if(!e)break;const{c:i,next:u}=e;a.push({id:i.rule.id,name:i.rule.name,tags:i.rule.tags,from:r.s,to:u.s,path:i.path,before:i.before.s,after:i.after.s,explanation:qt(i.rule,i.bound,ze(i.after),t)}),r=u,o.add(r.s)}return{node:r,steps:a}}finally{dt.variable=o}}const Nt={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 At(e){if(!1===e)return null;if(void 0===e||!0===e)return{show:"all",hide:Nt.normal,explain:!0};if("string"==typeof e){if(!Nt[e])throw new Error(`steps: "${e}" is not one of ${Object.keys(Nt).join(", ")}`);return{show:"all",hide:Nt[e],explain:!0}}const n=e.detail??"normal";if(!Nt[n])throw new Error(`steps.detail: "${n}" is not one of ${Object.keys(Nt).join(", ")}`);return{show:e.show??"all",hide:[...Nt[n],...e.hide??[]],explain:e.explain??!0}}function It(e,n){if(!n)return[];const t=[];let s=null;for(const i of e){if(!(Ot(i,n.show)&&!Ot(i,n.hide))){s=s??{from:i.from,ids:[]},s.ids.push(i.id);continue}const e={...i};s&&(e.from=s.from,e.also=s.ids,e.path=null,s=null);!0===n.explain||!1!==n.explain&&Ot(i,n.explain)||delete e.explanation,t.push(e)}if(s&&t.length){const n=t[t.length-1];n.to=e[e.length-1].to,n.also=[...n.also??[],...s.ids]}return t}const Et=X(V.ONE),Tt=(e,n)=>"atom"===e.k&&"sym"===e.node.type&&e.node.token===n;function jt(e){switch(e.k){case"num":default:return e;case"atom":return"op"===e.node.type?Ee(e.node.op,e.node.args.map(e=>jt(je(e)))):e;case"add":return de(Ue(e).map(jt));case"mul":{let n=[X(e.c)];for(const t of e.fs){const e=jt(t.b);if("add"===e.k&&se(t.e)&&t.e.q.isInteger&&t.e.q.sign>0&&t.e.q.n<=BigInt(60))for(let s=0n;s<t.e.q.n;s++)n=zt(n,Ue(e));else n=zt(n,[be(e,t.e)])}return de(n)}}}function zt(e,n){const t=[];for(const s of e)for(const e of n)t.push(ge([s,e]));return Ue(de(t))}function Zt(e,n){const t=new Map;for(const s of Ue(jt(e))){const{coef:e,rest:i}=he(s);let r=0;const o=[X(e)];for(const e of i?Ve(i):[]){const{b:t,e:s}="mul"===e.k&&1===e.fs.length&&e.c.isOne?e.fs[0]:{b:e,e:Et};if(Tt(t,n)){if(!se(s)||!s.q.isInteger||s.q.sign<0)return null;r+=Number(s.q.n)}else{if(Ft(t,n)||Ft(s,n))return null;o.push(e)}}t.set(r,de([t.get(r)??X(V.ZERO),ge(o)]))}for(const[e,n]of t)se(n)&&n.q.isZero&&t.delete(e);return t}const Ft=(e,n)=>Re(De(e)).has(n);function Bt(e){if(!e)return null;const n=Math.max(0,...e.keys());if(n>256)return null;const t=[];for(let s=0;s<=n;s++){const n=e.get(s)??X(V.ZERO);if(!se(n))return null;t.push(n.q)}return t}function Dt(e,n){const t=je(k(n));return de(e.map((e,n)=>ge([X(e),ve(t,X(V.of(n)))])))}const Ct=e=>{const n=e.slice();for(;n.length>1&&n[n.length-1].isZero;)n.pop();return n},Pt=(e,n)=>e.reduceRight((e,t)=>e.mul(n).add(t),V.ZERO);function Rt(e,n){const t=e.length-1,s=new Array(t);let i=V.ZERO;for(let r=t;r>=1;r--)i=e[r].add(i.mul(n)),s[r-1]=i;return s}function Ut(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 s=0;for(;t%e===0n;)t/=e,s++;n.push([e,s])}t>1n&&n.push([t,1]);let s=[1n];for(const[e,t]of n){const n=[];for(const i of s)for(let s=0,r=1n;s<=t;s++,r*=e)n.push(i*r);if(s=n,s.length>2e4)return null}return s.sort((e,n)=>e<n?-1:e>n?1:0)}function Vt(e){let n=Ct(e);const t=[];for(;n.length>1&&n[0].isZero;)t.push(V.ZERO),n=n.slice(1);if(n.length<=1)return{roots:t,rest:n};const s=n.reduce((e,n)=>e*n.d/U(e,n.d),1n),i=n.map(e=>e.n*s/e.d),r=Ut(i[0]),o=Ut(i[i.length-1]);if(!r||!o)return{roots:t,rest:n};const a=new Map;for(const e of r)for(const n of o)for(const t of[1n,-1n]){const s=new V(t*e,n);a.set(s.toString(),s)}const u=[...a.values()].sort((e,n)=>e.compare(n));for(const e of u)for(;n.length>1&&Pt(n,e).isZero;)t.push(e),n=Rt(n,e);return{roots:t.sort((e,n)=>e.compare(n)),rest:n}}function Lt(e,n){const t=Ct(n);let s=Ct(e);const i=t[t.length-1];if(i.isZero)throw new D("division by the zero polynomial");const r=new Array(Math.max(1,s.length-t.length+1)).fill(V.ZERO);for(;s.length>=t.length&&(1!==s.length||!s[0].isZero);){const e=s.length-t.length,n=s[s.length-1].div(i);if(r[e]=n,s=Ct(s.map((s,i)=>i>=e&&i-e<t.length?s.sub(n.mul(t[i-e])):s)),s.length-1<e+t.length-1&&s[s.length-1].isZero)break;if(s.length<t.length)break}return{q:Ct(r),r:s}}function Wt(e){if("num"===e.k)return{coef:e.q,factors:[],notes:[]};if("atom"===e.k)return{coef:V.ONE,factors:[{base:e,exp:Et}],notes:[]};if("mul"===e.k){let n=e.c;const t=[],s=[];for(const i of e.fs)if("add"===i.b.k&&se(i.e)&&i.e.q.isInteger){const e=Wt(i.b);n=n.mul(e.coef.pow(i.e.q.n));for(const n of e.factors)t.push({base:n.base,exp:ge([n.exp,i.e])});s.push(...e.notes)}else t.push({base:i.b,exp:i.e});return _t(n,t,s)}return function(e){const n=Ue(e),t=[],s=n.map(e=>{const{coef:n,rest:t}=he(e);return{coef:n,fs:t?Ve(t).map(Qt):[]}}),i=s.reduce((e,n)=>({n:U(e.n,n.coef.n),d:e.d*n.coef.d/U(e.d,n.coef.d)}),{n:0n,d:1n});let r=new V(i.n||1n,i.d);Ht(e)<0&&(r=r.neg());const o=[];for(const e of s[0].fs){if(!se(e.e)||e.e.q.sign<=0)continue;let n=e.e.q;const t=oe(e.b);let i=!0;for(const e of s.slice(1)){const s=e.fs.find(e=>oe(e.b)===t&&se(e.e)&&e.e.q.sign>0);if(!s){i=!1;break}s.e.q.compare(n)<0&&(n=s.e.q)}i&&o.push({base:e.b,exp:X(n)})}let a=e;if(!r.isOne||o.length){const e=ge([X(r),...o.map(e=>be(e.base,e.exp))]);a=de(n.map(n=>ge([n,ve(e,X(V.MINUS_ONE))]))),t.push({id:"factor.common",values:{common:e}})}const u="add"===a.k?function(e,n){const t=[...Jt(e)];for(const s of t){const i=Bt(Zt(e,s));if(!i||i.length<3)continue;if(1!==t.length)break;const{roots:r,rest:o}=Vt(i);if(!r.length)break;const a=[];let u=o[o.length-1]??V.ONE;const l=o.map(e=>e.div(u)),c=[...r].sort((e,n)=>e.abs().compare(n.abs())||n.sign-e.sign);for(const e of c){const t=Dt([new V(-e.n),new V(e.d)],s);a.push({base:t,exp:Et}),u=u.div(new V(e.d)),n.push({id:"factor.root",values:{root:X(e),factor:t}})}if(l.length>1){const e=l.reduce((e,n)=>e*n.d/U(e,n.d),1n),n=l.map(n=>n.mul(new V(e))),t=n.reduce((e,n)=>U(e,n.n),0n)||1n;u=u.mul(new V(t,e)),a.push({base:Dt(n.map(e=>e.div(new V(t))),s),exp:Et})}return _t(u,a,[])}const s=Ue(e);if(2===s.length){const[e,t]=s;for(const s of[2,3]){const i=Yt(e,s),r=Yt(Ne(t),s),o=3===s?Yt(t,s):null;if(i&&r&&2===s){n.push({id:"factor.squares",values:{a:i,b:r}});const e=Wt(de([i,Ne(r)])),t=Wt(de([i,r]));return _t(e.coef.mul(t.coef),[...e.factors,...t.factors],[...e.notes,...t.notes])}if(3===s&&i&&(r||o)){const e=r??o,t=r?-1:1;n.push({id:t<0?"factor.cubes-difference":"factor.cubes-sum",values:{a:i,b:e}});const s=de(t<0?[i,Ne(e)]:[i,e]),a=de([ve(i,X(V.of(2))),t<0?ge([i,e]):Ne(ge([i,e])),ve(e,X(V.of(2)))]),u=Wt(s);return _t(u.coef,[...u.factors,{base:a,exp:Et}],u.notes)}}}return{coef:V.ONE,factors:[{base:e,exp:Et}],notes:[]}}(a,t):Wt(a);return _t(r.mul(u.coef),[...o,...u.factors],[...t,...u.notes.filter(e=>!t.includes(e))])}(e)}function _t(e,n,t){const s=new Map;for(const e of n){const n=oe(e.base),t=s.get(n);t?t.exp=de([t.exp,e.exp]):s.set(n,{...e})}return{coef:e,factors:[...s.values()].filter(e=>!(se(e.exp)&&e.exp.q.isZero)),notes:t}}const Ht=e=>he(Ue(e)[0]).coef.sign;const Qt=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length?{b:e.fs[0].b,e:e.fs[0].e}:{b:e,e:Et},Jt=e=>Re(De(e));function Yt(e,n){const{coef:t,rest:s}=he(e);if(t.sign<0)return null;const i=function(e,n){const t=e=>{if(e<0n)return null;let t=0n,s=1n;for(;s**BigInt(n)<=e;)s*=2n;for(;t<s-1n;){const i=(t+s)/2n;i**BigInt(n)<=e?t=i:s=i}return t**BigInt(n)===e?t:null},s=t(e.n),i=t(e.d);return null!==s&&null!==i?new V(s,i):null}(t,n);if(!i)return null;const r=[X(i)];for(const e of s?Ve(s).map(Qt):[]){if(!se(e.e))return null;const t=e.e.q.div(V.of(n));if(!t.isInteger)return null;r.push(be(e.b,X(t)))}return ge(r)}function Kt({coef:e,factors:n}){const t=[],s=[];for(const e of n){const n=se(e.exp)&&e.exp.q.sign<0,i=n?X(e.exp.q.neg()):e.exp,r=De(be(e.base,i));(n?s:t).push(r)}const i=e=>e.reduce((e,n)=>e?N("*",[e,n]):n,null),r=e.n<0n?-e.n:e.n;let o=t.length?i(1n===r?t:[De(X(new V(r))),...t]):De(X(new V(r)));return e.n<0n&&(o=N("neg",[o])),1n!==e.d&&s.unshift(De(X(new V(e.d)))),s.length?N("/",[o,i(s)]):o}function Gt(e){if("mul"!==e.k)return{num:e,den:Et};const n=[X(new V(e.c.n))],t=[X(new V(e.c.d))];for(const s of e.fs)se(s.e)&&s.e.q.sign<0?t.push(be(s.b,X(s.e.q.neg()))):n.push(be(s.b,s.e));return{num:ge(n),den:ge(t)}}function Xt(e){if("add"!==e.k)return Gt(e);const n=Ue(e).map(Gt),t=new Map;let s=1n;for(const e of n){const{coef:n,rest:i}=he(e.den);s=s*n.n/U(s,n.n);for(const e of i?Ve(i).map(Qt):[]){const n=oe(e.b),s=t.get(n);(!s||se(e.e)&&se(s.e)&&e.e.q.compare(s.e.q)>0)&&t.set(n,e)}}const i=ge([X(new V(s)),...[...t.values()].map(e=>be(e.b,e.e))]);if(se(i)&&i.q.isOne)return{num:e,den:Et};return{num:jt(de(n.map(e=>ge([e.num,i,ve(e.den,X(V.MINUS_ONE))])))),den:i}}function es(e){const{num:n,den:t}=Xt(e);if(se(t)&&t.q.isOne)return null;const s=Wt(n),i=Wt(t),r=new Set(s.factors.map(e=>oe(e.base))),o=i.factors.filter(e=>r.has(oe(e.base))),a=[...s.factors,...i.factors.map(e=>({base:e.base,exp:Ne(e.exp)}))];return{..._t(s.coef.div(i.coef),a,[...s.notes,...i.notes]),canceled:o.map(e=>e.base)}}const ns=(e,n)=>N("=",[e,n]),ts=ze(N("+",[k("x"),N("neg",[k("x")])])),ss=e=>A(e)&&"="===e.op;function is(e,n,t,s={}){const i=[],r=(n,t,s,r,o,a={})=>i.push(e.step(n,t,s,r,o,a));r.raw=e=>i.push(e);const o=ss(n)?n:ns(n,ts),a=ns(ze(o.args[0]),ze(o.args[1]));a.s!==o.s&&r("normal","Work out each side",["tidy","arithmetic"],o,a);const u=[],l=[],c=new Set;u.numeric=c,cs(e,a,t,s,r,u,l,0);const f=[],p=new Set;for(const n of u.map(n=>c.has(n)?n:(n=>Mt(n,e.set.view("simplify"),{format:e.format}).node)(n))){const e=n.s;if(p.has(e))continue;p.add(e);const s=c.has(n)?null:as(o,t,n);s?r("solve.reject","Check the answer",["check"],ns(k(t),n),ns(k(t),n),{value:n,reason:s}):f.push(n)}return f.sort(rs),{solutions:f,unsolved:l,steps:i,always:l.some(e=>e.always)}}function rs(e,n){const t=os(e),s=os(n);return null===t||null===s?e.s<n.s?-1:1:(Math.abs(t.im)>0)-(Math.abs(s.im)>0)||t.re-s.re||t.im-s.im}function os(e){if(Re(e).size)return null;try{const{re:n,im:t}=ct(e,{digits:20});return{re:n,im:t}}catch{return null}}function as(e,n,t){const[s,i]=e.args,r=new Set([...Re(s),...Re(i),...Re(t)]);if(r.delete(n),r.size)return null;const o=e=>us(e,n,t);try{const e=ct(o(s),{digits:40}),n=ct(o(i),{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 us(e,n,t){return"sym"===e.type?e.token===n?t:e:A(e)?N(e.op,e.args.map(e=>us(e,n,t))):e}const ls=24;function cs(e,n,t,s,i,r,o,a){if(a>ls)return vs(e,n,t,s,i,r,o);const u=function(e){const n=[],t=e=>{if(A(e)&&"|"===e.op)return void e.args.forEach(t);if(!ss(e))return void n.push(e);const s=e.args[1],i=F(s,"pre").find(({node:e})=>A(e)&&"pm"===e.op);if(!i)return void n.push(e);const r=i.node.args[0],o=ze(B(s,i.path,r)),a=ze(B(s,i.path,N("neg",[r])));t(ns(e.args[0],o)),a.s!==o.s&&t(ns(e.args[0],a))};return t(e),n}(n);if(u.length>1){i("solve.split","Two cases",["split"],n,u.reduce((e,n)=>e?N("|",[e,n]):n,null));for(const n of u)cs(e,n,t,s,i,r,o,a+1);return}if(1===u.length&&u[0].s!==n.s)return cs(e,u[0],t,s,i,r,o,a+1);const[l,c]=n.args;if("sym"===l.type&&l.token===t&&!Ft(je(c),t))return void r.push(c);const f=de([je(l),Ne(je(c))]);if(!Ft(f,t))return se(f)&&f.q.isZero?(i("solve.always","Always true",["check"],n,n,{v:t}),void o.push(Object.assign(Object.create(n),{always:!0}))):void i("solve.never","No solution",["check"],n,n,{v:t});const p=Ue(f).filter(e=>Ft(e,t)),h=Ue(f).filter(e=>!Ft(e,t)),d=de(p),m=Ne(de(h));if(J.complex){const u=Zt(f,t);if(u&&[...u.values()].every(e=>!Ft(e,t))&&Math.max(...u.keys())>=2){const l=ns(De(f),ts);return l.s!==n.s&&i("solve.one-side","Everything on one side",["move"],n,l,{v:t}),ms(e,f,u,t,s,i,r,o,a,l)}}if(1===p.length)return fs(e,n,d,m,t,s,i,r,o,a);const g=ns(De(f),ts),v=Zt(f,t);if(v&&[...v.values()].every(e=>!Ft(e,t))&&Math.max(...v.keys())>=2)return g.s!==n.s&&i("solve.one-side","Everything on one side",["move"],n,g,{v:t}),ms(e,f,v,t,s,i,r,o,a,g);const b=Wt(f),w=b.factors.filter(e=>Ft(e.base,t)&&!(se(e.exp)&&e.exp.q.sign<0));if(w.length>=2||1===w.length&&b.factors.length>1){const u=ns(Kt(b),ts);g.s!==n.s&&i("solve.one-side","Everything on one side",["move"],n,g,{v:t}),u.s!==g.s&&i("solve.factor","Factor",["factor"],g,u,{});const l=w.map(e=>ns(De(e.base),ts));l.length>1&&i("solve.zero-product","A product is zero when a factor is",["split"],u,l.reduce((e,n)=>e?N("|",[e,n]):n,null),{});for(const n of l)cs(e,n,t,s,i,r,o,a+1);return}const y=Xt(f);if(Ft(y.den,t)){const u=ns(De(y.num),ts);return i("solve.clear-denominator","Clear the denominator",["move"],n,u,{den:De(y.den)}),cs(e,u,t,s,i,r,o,a+1)}const x=p.filter(e=>!ds(e,t));if(1===x.length&&/\b(sqrt|root|abs)\b/.test(De(x[0]).s))return fs(e,n,x[0],Ne(de(Ue(f).filter(e=>e!==x[0]))),t,s,i,r,o,a);const q=function(e,n){const t=De(e),s=new Map;for(const{node:e}of F(t,"pre"))if(A(e)&&Re(e).has(n))if("^"!==e.op||Re(e.args[0]).has(n))["sin","cos","tan","ln","sqrt","abs"].includes(e.op)&&e.args[0].s===n&&s.set(e.s,e);else{const t=je(e.args[1]),{coef:i,rest:r}=he(t);if(r&&i.isInteger&&De(r).s===n){const t=De(ve(je(e.args[0]),je(k(n))));s.set(t.s,t)}}const i="u"===n?"w":"u";for(const e of s.values()){const s=gs(t,e,n,i);if(!s||Re(s).has(n))continue;const r=je(s),o=Zt(r,i);if(o&&Math.max(...o.keys())>=1)return{kernel:je(e),poly:r,symbol:i}}return null}(f,t);if(q){const n=q.symbol;i("solve.substitute","Substitute",["substitute"],g,ns(De(q.poly),ts),{u:k(n),kernel:De(q.kernel)});const u=[];cs(e,ns(De(q.poly),ts),n,s,i,u,o,a+1);for(const n of u)cs(e,ns(De(q.kernel),n),t,s,i,r,o,a+1);return}return vs(e,g,t,s,i,r,o)}function fs(e,n,t,s,i,r,o,a,u,l){let c=ns(De(t),De(s));c.s!==n.s&&o("solve.move","Move the terms",["move"],n,c,{v:i});const{coef:f,rest:p}=he(t),h=p?Ve(p):[],d=ge([X(f),...h.filter(e=>!Ft(e,i))]);if(!se(d)||!d.q.isOne){const e=ge(h.filter(e=>Ft(e,i))),n=ns(De(e),De(Oe(s,d))),t=se(d)&&!d.q.isInteger&&(1n===d.q.n||-1n===d.q.n);o(t?"solve.multiply":"solve.divide",t?"Multiply both sides":"Divide both sides",["move"],c,n,{by:De(t?X(d.q.inv()):d),v:i}),c=n}if("sym"===c.args[0].type&&c.args[0].token===i)return void a.push(c.args[1]);const m=je(c.args[1]);if(se(m)&&m.q.isZero){const n=je(c.args[0]),t=Ve(n).filter(e=>Ft(e,i)&&!ps(e));if(!t.length&&Ve(n).some(e=>Ft(e,i)))return void o("solve.never","No solution",["check"],c,c,{});if(t.length>1||t.length<Ve(n).filter(e=>Ft(e,i)).length){const n=t.map(e=>ns(De(hs(e)),ts));o("solve.zero-product","A product is zero when a factor is",["split"],c,n.reduce((e,n)=>e?N("|",[e,n]):n,null),{});for(const t of n)cs(e,t,i,r,o,a,u,l+1);return}}const g=Mt(c,e.set.view("isolate"),{format:e.format,maxSteps:1,variable:i});return g.steps.length?(function(e,n){for(const t of n)e.raw(t)}(o,g.steps),cs(e,g.node,i,r,o,a,u,l+1)):vs(e,c,i,r,o,a,u)}const ps=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&se(e.fs[0].e)&&e.fs[0].e.q.sign<0,hs=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&se(e.fs[0].e)&&e.fs[0].e.q.sign>0?e.fs[0].b:e,ds=(e,n)=>{const t=Zt(e,n);return Boolean(t)&&[...t.values()].every(e=>!Ft(e,n))};function ms(e,n,t,s,i,r,o,a,u,l){const c=Math.max(...t.keys()),f=Bt(t);if(J.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=ve(X(n.abs()),X(new V(1n,BigInt(c)))),i=[];for(let s=0;s<c;s++){const r=ge([X(new V(BigInt((n.sign<0?1:0)+2*s),BigInt(c))),je(k("pi"))]),o=N("*",[De(t),N("+",[N("cos",[De(r)]),N("*",[k("i"),N("sin",[De(r)])])])]);i.push(Mt(o,e.set.view("simplify"),{format:e.format}).node)}return r("solve.roots","All n roots",["complex"],l,i.map(e=>ns(k(s),e)).reduce((e,n)=>e?N("|",[e,n]):n),{v:s,n:String(c),last:String(c-1),r:De(X(n))}),void o.push(...i)}if(f){const{roots:t}=Vt(f);if(t.length){const t=Wt(n),c=ns(Kt(t),ts);if(t.factors.length>1||t.factors.some(e=>!(se(e.exp)&&e.exp.q.isOne))){r("solve.factor","Factor",["factor"],l,c,{});const n=t.factors.filter(e=>Ft(e.base,s)).map(e=>ns(De(e.base),ts));n.length>1&&r("solve.zero-product","A product is zero when a factor is",["split"],c,n.reduce((e,n)=>e?N("|",[e,n]):n,null),{});for(const t of n)cs(e,t,s,i,r,o,a,u+1);return}}}if(2===c){const e=t.get(2),n=t.get(1)??X(V.ZERO),i=t.get(0)??X(V.ZERO),a=de([ve(n,X(V.of(2))),ge([X(V.of(-4)),e,i])]);if(se(a)&&a.q.sign<0&&!J.complex)return void r("solve.no-real","No real solutions",["quadratic"],l,l,{D:De(a)});const u=ge([X(V.of(2)),e]),c=ve(a,X(V.HALF)),f=De(Oe(de([Ne(n),c]),u)),p=De(Oe(de([Ne(n),Ne(c)]),u)),h=f.s===p.s?ns(k(s),f):N("|",[ns(k(s),f),ns(k(s),p)]);return r(J.complex&&se(a)&&a.q.sign<0?"solve.quadratic-complex":"solve.quadratic","The quadratic formula",["quadratic"],l,h,{a:De(e),b:De(n),c:De(i),D:De(a),root:De(c),v:s}),o.push(f),void(p.s!==f.s&&o.push(p))}return vs(e,l,s,i,r,o,a)}function gs(e,n,t,s){if(e.s===n.s)return k(s);if(!A(e))return e;if("^"===e.op&&"^"===n.op&&e.args[0].s===n.args[0].s){const n=je(e.args[1]),{coef:i,rest:r}=he(n);if(r&&De(r).s===t&&i.isInteger)return N("^",[k(s),De(X(i))])}return N(e.op,e.args.map(e=>gs(e,n,t,s)))}function vs(e,n,t,s,i,r,o){if(s.approximate){const e="number"==typeof s.approximate?s.approximate:15,o=je(N("-",[n.args[0],n.args[1]])),a=J.complex?Bt(Zt(o,t)):null,u=a&&a.length>2?function(e,n){const t=e.length-1,s=e[t],i=e.map(e=>e/s),r=(e,n)=>{let s=1,r=0;for(let o=t-1;o>=0;o--)[s,r]=[s*e-r*n+i[o],s*n+r*e];return[s,r]};let o=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(o=o.map(([n,s],i)=>{let[a,u]=r(n,s);for(let e=0;e<t;e++){if(e===i)continue;const t=n-o[e][0],r=s-o[e][1],l=t*t+r*r;[a,u]=[(a*t+u*r)/l,(u*t-a*r)/l]}return e=Math.max(e,Math.hypot(a,u)),[n-a,s-u]}),e<1e-15)break}const a=e=>Math.abs(e)<1e-12?0:Number(e.toPrecision(n));return o.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=bs(e);if(0===n)return t;const s=N("*",[bs(Math.abs(n)),k("i")]);return 0===e?n<0?N("neg",[s]):s:N(n<0?"-":"+",[t,s])})}(a.map(e=>e.toNumber()),Math.min(e,14)):function(e,n,t){const s=je(N("-",[e.args[0],e.args[1]])),i=De(s),r=e=>{try{return ct(us(i,n,ws(e)),{digits:30}).number}catch{return NaN}},o=[],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],s=a[e+1],i=r(n);const u=r(s);if(Number.isNaN(i)||Number.isNaN(u))continue;if(0===i){o.push(ws(n));continue}if(i*u>0)continue;for(let e=0;e<200&&s-n>1e-16*Math.abs(n);e++){const e=(n+s)/2,t=r(e);if(Number.isNaN(t))break;i*t<=0?s=e:(n=e,i=t)}const l=(n+s)/2;Math.abs(r(l))<1e-6&&o.push(ws(Number(l.toPrecision(Math.min(t,15)))))}return o}(n,t,e);for(const e of u)r.numeric?.add(e);return i("solve.numeric","Numeric solutions",["numeric"],n,u.length?u.map(e=>ns(k(t),e)).reduce((e,n)=>e?N("|",[e,n]):n):n,{v:t,count:String(u.length)}),void r.push(...u)}i("solve.unsolved","No exact method",["unsolved"],n,n,{v:t}),o.push(n)}const bs=e=>$(String(e).includes("e")?e.toFixed(20):String(e)),ws=e=>$(Number.isInteger(e)?String(e):e.toFixed(17));const ys=()=>$("1"),xs={"<":e=>e<0,">":e=>e>0,"≤":e=>e<=0,"≥":e=>e>=0},qs=new Set(["sin","cos","tan","csc","sec","cot"]);function ks(e,n,t){const s=[],i=[],r=[];let o=n;for(;A(o.args[0])&&xs[o.args[0].op];)r.unshift({op:o.op,right:o.args[1]}),o=o.args[0];const a=[o.args[0],o.args[1],...r.map(e=>e.right)];[o.op,...r.map(e=>e.op)].forEach((e,n)=>i.push({h:ze(N("-",[a[n],a[n+1]])),op:e}));const u=new Set(i.flatMap(e=>[...Re(e.h)]));if(u.delete(t),u.size)throw new D(`an inequality in ${t} with other unknowns (${[...u].join(", ")}) can't be charted`);if(i.some(e=>F(e.h,"pre").some(({node:e})=>A(e)&&qs.has(e.op)&&Re(e).has(t))))return{pieces:null,steps:s,unsolved:!0};const l=[];for(const{h:e}of i){l.push(e);for(const{node:n}of F(e,"pre"))A(n)&&Re(n).has(t)&&("/"===n.op&&l.push(n.args[1]),"sqrt"!==n.op&&"ln"!==n.op||l.push(n.args[0]),"root"===n.op&&l.push(n.args[1]),"log"===n.op&&l.push(n.args[1],n.args[0],N("-",[n.args[0],ys()])),["arcsin","arccos","arctanh","arcsec","arccsc"].includes(n.op)&&l.push(N("-",[n.args[0],ys()]),N("+",[n.args[0],ys()])),"arccosh"===n.op&&l.push(N("-",[n.args[0],ys()])),"^"===n.op&&se(je(n.args[1]))&&je(n.args[1]).q.sign<0&&l.push(n.args[0]),"^"===n.op&&se(je(n.args[1]))&&!je(n.args[1]).q.isInteger&&l.push(n.args[0]))}const c=new Map;for(const n of l){const i=is(e,ns(n,ts),t,{});if(i.unsolved.length&&!i.always)return{pieces:null,steps:s,unsolved:!0};if(!i.always)for(const e of i.solutions){const n=os(e);!n||Math.abs(n.im)>1e-12||c.set(e.s,{node:e,x:n.re})}}const f=[...c.values()].sort((e,n)=>e.x-n.x).filter((e,n,t)=>0===n||Math.abs(e.x-t[n-1].x)>1e-12),p=f.map(e=>e.x),h=[];if(p.length){h.push(p[0]-Math.max(1,Math.abs(p[0])));for(let e=0;e+1<p.length;e++)h.push((p[e]+p[e+1])/2);h.push(p[p.length-1]+Math.max(1,Math.abs(p[p.length-1])))}else h.push(0);const d=h.map(e=>i.every(({h:n,op:s})=>{try{const i=ct(us(n,t,$(function(e){return Math.abs(e)>=1e21?BigInt(Math.round(e)).toString():e.toFixed(Math.min(100,Math.max(0,17-Math.floor(Math.log10(Math.abs(e)||1)))))}(e))),{digits:20});return!(!Number.isFinite(i.re)||Math.abs(i.im)>1e-12)&&xs[s](Math.abs(i.re)<1e-30?0:i.re)}catch{return!1}})),m=f.map(e=>i.every(({h:n,op:s})=>{try{const i=ct(ze(us(n,t,e.node)),{digits:30});return!(!Number.isFinite(i.re)||Math.abs(i.im)>1e-12)&&xs[s](Math.abs(i.re)<1e-15?0:i.re)}catch{return!1}})),g=[];let v=null;const b=(e,n)=>{g.push({...v,hi:e,hiClosed:n}),v=null};for(let e=0;e<=f.length;e++){const n=0===e?null:f[e-1].node;if(d[e]?v??={lo:n,loClosed:!1}:v&&b(n,e>0&&m[e-1]),e===f.length)break;const t=f[e];if(m[e]){if(v)continue;d[e+1]?v={lo:t.node,loClosed:!0}:g.push({lo:t.node,hi:t.node,loClosed:!0,hiClosed:!0})}else v&&b(t.node,!1)}v&&b(null,!1);const w=f.length?f.map(n=>e.format(n.node)).join(", "):"none";return s.push(e.step("solve.sign-chart","A sign chart",["inequality"],n,n,{points:k(w),v:t})),{pieces:g,steps:s}}const $s={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};class Ss extends Error{}const Ms=e=>({fin:e}),Ns={bnd:!0},Os=e=>({inf:e}),As=k("∞");function Is(e){try{const n=ct(e,{digits:15});return Math.abs(n.im??0)>1e-12?NaN:n.re??n.number}catch{return NaN}}function Es(e){if(!J.complex)return Number.isFinite(Is(e));try{const n=ct(e,{digits:15});return Number.isFinite(n.re??n.number)&&Number.isFinite(n.im??0)}catch{return!1}}function Ts(e,n,t){if(!Number.isFinite(t))return!1;try{const s=ct(us(e,n,$(zs(t))),{digits:15});return Math.abs(s.im??0)>1e-12}catch(e){return/not real/.test(e.message)}}function js(e,n,t){return Number.isFinite(t)?Is(us(e,n,$(zs(t)))):NaN}function zs(e){const n=Math.min(40,Math.max(0,16-Math.floor(Math.log10(Math.abs(e)||1))));return e.toFixed(n)}function Zs(e,n,t,s){const i=Fs(t,s).map(t=>js(e,n,t)).filter(Number.isFinite);if(i.length<3)return NaN;const[r,o,a]=i.slice(-3),u=Math.max(1,Math.abs(a));return Math.abs(a-o)<1e-4*u&&Math.abs(o-r)<.01*u?a:NaN}function Fs(e,n){if(e.inf)return[100,1e3,1e4,1e5,1e6].map(n=>n*e.inf);const t=Is(e.fin);return[.001,1e-4,1e-5,1e-6,1e-7].map(e=>t+n*e*Math.max(1,Math.abs(t)))}function Bs(e,n,t,s,i=0){const r=[];if(!i&&!s.inf){const[e,i]=[Zs(n,t,s,-1),Zs(n,t,s,1)];if(Number.isFinite(e)&&Number.isFinite(i)&&Math.abs(e-i)>.001*Math.max(1,Math.abs(e),Math.abs(i)))throw new Ss(`from the left it goes to ${+e.toPrecision(6)}, from the right to ${+i.toPrecision(6)}`)}if(!s.inf&&!J.complex)for(const e of i?[i]:[-1,1])if(Fs(s,e).every(e=>Ts(n,t,e)))throw new Ss(`it has no real values ${e<0?"to the left":"to the right"} of ${+Is(s.fin).toPrecision(6)}`);const o=new Ds(e,t,s,i,r);let a;try{if(a=o.of(ze(n),0),a.bnd)throw new Ss("it keeps swinging between bounds")}catch(e){if(e instanceof Ss){const e=(s.inf?[s.inf]:i?[i]:[-1,1]).map(e=>Zs(n,t,s,e));if(e.every(Number.isFinite)&&e.every(n=>Math.abs(n-e[0])<1e-6*Math.max(1,Math.abs(n))))throw new D(`numbers near the point settle on ${+e[0].toPrecision(6)}: not answered`)}throw e}return function(e,n,t,s,i){const r=s?[s]:t.inf?[-1]:[-1,1];for(const s of r){const r=Fs(t,s).map(t=>js(e,n,t)).filter(Number.isFinite);if(r.length<3)continue;const o=r[r.length-1];if(i.inf){if(Math.sign(o)!==i.inf||Math.abs(o)<Math.abs(r[0]))throw new D(`numbers near the point don't go to ${i.inf>0?"∞":"-∞"}: not answered`)}else{const e=Is(i.fin);if(!Number.isFinite(e))continue;const n=r.map(n=>Math.abs(n-e)),t=Math.abs(r[r.length-1]-r[r.length-2]),s=n.every((e,t)=>0===t||e<n[t-1])&&n[n.length-1]<.5*n[0]&&n[n.length-1]<10*t;if(n[n.length-1]>.01*Math.max(1,Math.abs(e))&&!s)throw new D(`numbers near the point go to ${o.toPrecision(6)}, not ${e.toPrecision(6)}: not answered`)}}}(n,t,s,i,a),{value:a,steps:r}}class Ds{constructor(e,n,t,s,i){Object.assign(this,{cas:e,v:n,a:t,side:s,steps:i}),this.point=t.inf?t.inf>0?As:k("-∞"):t.fin}step(e,n,t,s,i={}){this.steps.push(this.cas.step(e,n,["limit"],t,s,{v:k(this.v),a:this.point,...i}))}of(e,n){if(n>8)throw new D("this limit went too deep");const{v:t,a:s}=this;if(!Re(e).has(t))return Ms(e);if("sym"===e.type)return s.inf?Os(s.inf):Ms(s.fin);if(s.inf){const i=Bt(Zt(je(e),t));if(i&&i.length>1){const r=i.length-1,o=i[r].sign*(r%2&&s.inf<0?-1:1);return 0===n&&this.step("limit.leading","The leading term",e,ze(N("*",[De(X(i[r])),N("^",[k(t),$(String(r))])])),{f:e,lead:ze(N("*",[De(X(i[r])),N("^",[k(t),$(String(r))])]))}),Os(o)}}if(!s.inf&&0===n){const n=us(e,t,s.fin);let i=null;if(Es(n)&&!this.pole(n)&&!Cs(n))try{i=ze(n)}catch{}if(i&&Es(i)){const n=this.cas.simplify(i,{steps:!1}).result;return this.step("limit.substitute","Put the point in",e,n,{f:e}),Ms(n)}}if(!A(e))return Ms(e);switch(e.op){case"+":case"-":return this.sum(e,n);case"neg":return Rs(this.of(e.args[0],n+1));case"*":return this.product(e,n);case"/":return this.quotient(e,e.args[0],e.args[1],n);case"^":return this.power(e,n);default:return this.func(e,n)}}signOf(e){const n=Math.sign(Is(e));if(!n)throw new D(`the sign of ${this.cas.format(e)} is not known`);return n}pole(e){return Ps(e).some(e=>A(e)&&$s[e.op]&&this.isExactZero(N($s[e.op],[e.args[0]])))}isExactZero(e){try{const n=this.cas.simplify(ze(e),{steps:!1}).result;return O(n)&&0===Number(n.value)}catch{return!1}}sum(e,n){const[t,s]=e.args;let i,r;try{i=this.of(t,n+1),r=this.of(s,n+1)}catch(t){if(!(t instanceof Ss))throw t;const s=Xt(je(e)),i=ze(N("/",[De(s.num),De(s.den)]));if(i.s===e.s)throw t;return this.step("limit.combine","One fraction",e,i,{f:e}),this.of(i,n+1)}const o="-"===e.op?Rs(r):r;if(i.bnd||o.bnd)return i.inf||o.inf?i.inf?i:o:Ns;if(i.fin&&o.fin)return Ms(ze(N("+",[i.fin,o.fin])));if(i.inf&&o.inf&&i.inf!==o.inf){const i="-"===e.op?s:N("neg",[s]);if([t,s].some(e=>A(e)&&"sqrt"===e.op)||A(s)&&"neg"===s.op&&A(s.args[0])&&"sqrt"===s.args[0].op){const s=ze(N("/",[N("-",[N("^",[t,$("2")]),N("^",[i,$("2")])]),N("+",[t,i])]));return this.step("limit.conjugate","∞ − ∞: the conjugate",e,s,{f:e}),this.of(s,n+1)}const r=Xt(je(e)),o=ze(N("/",[De(r.num),De(r.den)]));if(o.s===e.s)throw new D("∞ − ∞ that does not become one fraction");return this.step("limit.combine","∞ − ∞: one fraction",e,o,{f:e}),this.of(o,n+1)}return i.inf?i:o}product(e,n){const[t,s]=e.args,i=this.of(t,n+1),r=this.of(s,n+1),o=e=>e.fin&&Math.abs(Is(e.fin))<1e-300;if(i.bnd||r.bnd){const n=i.bnd?r:i;if(o(n))return this.step("limit.squeeze","The squeeze theorem",e,$("0"),{f:e,bounded:i.bnd?t:s}),Ms($("0"));if(n.inf)throw new Ss("a growing factor times one that keeps swinging");return Ns}if(i.fin&&r.fin)return Ms(ze(N("*",[i.fin,r.fin])));if(o(i)&&r.inf||i.inf&&o(r)){const[r,a]=o(i)?[t,s]:[s,t],u=e=>e.s.split(" ").length,[l,c]=[ze(N("/",[$("1"),r])),ze(N("/",[$("1"),a]))],f=u(l)<=u(c)?N("/",[a,l]):N("/",[r,c]);return this.step("limit.zero-times-infinity","0·∞: a quotient",e,f,{f:e}),this.quotient(f,f.args[0],f.args[1],n+1)}const a=e=>e.inf?e.inf:this.signOf(e.fin);return Os(a(i)*a(r))}quotient(e,n,t,s){const{v:i,a:r}=this;if(r.inf){const n=this.rational(e,s);if(n)return n}const o=this.of(n,s+1),a=this.of(t,s+1),u=e=>e.fin&&Math.abs(Is(e.fin))<1e-300;if(o.bnd&&a.inf)return this.step("limit.squeeze","The squeeze theorem",e,$("0"),{f:e,bounded:n}),Ms($("0"));if(o.bnd&&a.fin&&!u(a))return Ns;if(a.bnd)throw new D("a quotient over something that keeps swinging is not worked out here");if(o.inf&&a.inf&&r.inf){const i=this.dividePower(e,n,t,s);if(i)return i}if(a.fin&&!u(a))return o.fin?Ms(this.cas.simplify(ze(N("/",[o.fin,a.fin])),{steps:!1}).result):Os(o.inf*this.signOf(a.fin));if(a.inf&&o.fin)return Ms($("0"));if(u(a)&&!u(o))return this.blowUp(e);const l=u(o)?"0/0":"∞/∞",c=this.rational(e,s);if(c)return c;const f=ze(this.cas.differentiate(n,i)),p=ze(this.cas.differentiate(t,i)),h=ze(N("/",[f,p]));return this.step("limit.lhopital","L'Hôpital's rule",e,h,{f:e,form:k(l)}),this.of(h,s+1)}dividePower(e,n,t,s){const{v:i,a:r}=this;if(!Ps(e).some(e=>A(e)&&(["sqrt","root","sin","cos"].includes(e.op)||"^"===e.op&&!Re(e.args[1]).size&&!Number.isInteger(Is(e.args[1]))))||this.divided?.has(e.s))return null;const[o,a]=[1e4*r.inf,1e6*r.inf],u=Math.log(Math.abs(js(t,i,a)/js(t,i,o)))/Math.log(100),l=Math.round(2*u)/2;if(!Number.isFinite(u)||Math.abs(u-l)>.05||l<=0||r.inf<0&&!Number.isInteger(l))return null;const c=N("^",[k(i),$(String(l))]),f=e=>{if(A(e)&&("+"===e.op||"-"===e.op))return N(e.op,e.args.map(f));if(A(e)&&"neg"===e.op)return N("neg",[f(e.args[0])]);if(A(e)&&"sqrt"===e.op){const n=N("sqrt",[ze(N("/",[e.args[0],N("^",[k(i),$(String(2*l))])]))]);return r.inf<0&&l%2?N("neg",[n]):n}return ze(N("/",[e,c]))},p=N("/",[ze(f(n)),ze(f(t))]);return(this.divided??=new Set).add(e.s),this.step("limit.divide-power","Divide by the highest power",e,p,{f:e,power:c}),this.quotient(p,p.args[0],p.args[1],s+1)}rational(e,n){const{v:t,a:s}=this,{num:i,den:r}=Xt(je(e)),o=Bt(Zt(i,t)),a=Bt(Zt(r,t));if(!o||!a||a.length<2)return null;if(s.inf){const[n,i]=[o.length-1,a.length-1],r=ze(N("/",[N("*",[De(X(o[n])),N("^",[k(t),$(String(n))])]),N("*",[De(X(a[i])),N("^",[k(t),$(String(i))])])]));if(r.s!==e.s&&this.step("limit.leading","The leading terms",e,r,{f:e,lead:r}),n<i)return Ms($("0"));if(n===i)return Ms(De(X(o[n].div(a[i]))));const u=o[n].div(a[i]).sign*((n-i)%2&&s.inf<0?-1:1);return Os(u)}const u=this.cas.cancel(e,{steps:!1}).result;if(u.s===e.s)return null;this.step("limit.cancel","Cancel the common factor",e,u,{f:e});const l=us(u,t,s.fin);return Number.isFinite(Is(l))?Ms(this.cas.simplify(ze(l),{steps:!1}).result):this.blowUp(u)}blowUp(e){const{v:n,a:t,side:s}=this,i=(s?[s]:[-1,1]).map(s=>function(e,n,t,s){const i=Fs(t,s).map(t=>js(e,n,t)).filter(Number.isFinite);if(!i.length)return 0;const r=Math.sign(i[i.length-1]);return i.slice(-3).every(e=>Math.sign(e)===r)?r:0}(e,n,t,s));if(i.includes(0))throw new D("the sign near the point could not be told");if(2===i.length&&i[0]!==i[1])throw this.step("limit.one-sided","The two sides differ",e,e,{f:e,left:i[0]>0?As:k("-∞"),right:i[1]>0?As:k("-∞")}),new Ss(`from the left it goes to ${i[0]>0?"∞":"-∞"}, from the right to ${i[1]>0?"∞":"-∞"}`);return Os(i[0])}power(e,n){const{v:t}=this,[s,i]=e.args,r=this.of(s,n+1);let o;const a=this.steps.length;try{o=this.of(i,n+1)}catch(t){if(!(t instanceof Ss)||!r.fin||Math.abs(Is(r.fin)-1)>1e-12)throw t;return this.steps.length=a,this.expLog(e,s,i,"1^∞",n)}if(r.bnd||o.bnd)throw new D("a power of something that keeps swinging is not worked out here");const u=e=>e.fin?Is(e.fin):e.inf*(1/0),l=u(r),c=u(o);if(r.fin&&o.fin){if(Math.abs(l)<1e-300&&c<0)return this.blowUp(e);if(!(Math.abs(l)<1e-300&&Math.abs(c)<1e-300))return Ms(this.cas.simplify(ze(N("^",[r.fin,o.fin])),{steps:!1}).result)}const f=!Re(s).has(t),p=!Re(i).has(t),h=r.fin&&Math.abs(l)<1e-300,d=r.fin&&Math.abs(l-1)<1e-12;if(r.fin&&o.inf&&(!d||f)){if(d)return Ms($("1"));if(h){if(o.inf<0){if(f)throw new Ss("0 to a negative power has no value");return Os(1)}return Ms($("0"))}if(l>1)return o.inf>0?Os(1):Ms($("0"));if(l>0)return o.inf>0?Ms($("0")):Os(1);throw new Ss("a negative number to a growing power swings between signs")}if(r.inf<0&&!p)throw new D("a power of something going to -∞ is not worked out here");if(r.inf&&(p||o.fin&&Math.abs(c)>1e-300||o.inf)){if(c>0)return Os(r.inf>0?1:p&&Number.isInteger(c)&&c%2?-1:1);if(c<0)return Ms($("0"))}if(p&&h&&c>0)return Ms($("0"));const m=d?"1^∞":h?"0^0":r.inf&&o.fin?"∞^0":null;if(!m)throw new D("a power of this shape is not worked out here");return this.expLog(e,s,i,m,n)}expLog(e,n,t,s,i){const r=ze(N("*",[t,N("ln",[n])]));this.step("limit.exp-log","Take logs",e,N("^",[k("e"),r]),{f:e,form:k(s)});const o=this.of(r,i+1);if(o.bnd)throw new D("a power of something that keeps swinging is not worked out here");return o.inf?o.inf>0?Os(1):Ms($("0")):Ms(this.cas.simplify(ze(N("^",[k("e"),o.fin])),{steps:!1}).result)}func(e,n){const t=e.op,s=e.args;if(1!==s.length){if("log"===t&&!Re(s[0]).has(this.v)){const e=this.of(s[1],n+1);if(e.fin){const n=ze(N("log",[s[0],e.fin]));if(Number.isFinite(Is(n)))return Ms(this.cas.simplify(n,{steps:!1}).result)}return this.of(ze(N("/",[N("ln",[s[1]]),N("ln",[s[0]])])),n+1)}throw new D(`a limit of ${t} is not worked out here`)}let i;try{i=this.of(s[0],n+1)}catch(e){if(e instanceof Ss&&("sin"===t||"cos"===t))return Ns;throw e}if(i.bnd){if("sin"===t||"cos"===t||"arctan"===t||"abs"===t)return Ns;throw new D(`${t} of something that keeps swinging is not worked out here`)}if(i.fin){if($s[t]&&this.isExactZero(N($s[t],[i.fin])))return this.blowUp(e);const n=ze(N(t,[i.fin]));if(Es(n))return Ms(this.cas.simplify(n,{steps:!1}).result);if("ln"===t&&Math.abs(Is(i.fin))<1e-300)return Os(-1);if(["tan","sec","csc","cot"].includes(t))return this.blowUp(e);throw new D(`${t} has no value at the limit of its argument`)}const r=i.inf;switch(t){case"sqrt":case"ln":case"cosh":if(r<0&&"cosh"!==t)throw new Ss(`${t} has no value as its argument goes to -∞`);return Os(1);case"abs":return Os(1);case"sinh":return Os(r);case"tanh":return Ms($(String(r)));case"arctan":return Ms(ze(N("/",[r>0?k("pi"):N("neg",[k("pi")]),$("2")])));case"arccot":return Ms(r>0?$("0"):k("pi"));case"arcsec":case"arccsc":return Ms("arcsec"===t?ze(N("/",[k("pi"),$("2")])):$("0"));case"sin":case"cos":return Ns;case"tan":case"sec":case"csc":case"cot":throw new Ss(`${t} keeps swinging as its argument grows`);default:throw new D(`a limit of ${t} at ∞ is not worked out here`)}}}const Cs=e=>Ps(e).some(e=>A(e)&&("/"===e.op&&Math.abs(Is(e.args[1]))<1e-300||"^"===e.op&&Is(e.args[1])<0&&Math.abs(Is(e.args[0]))<1e-300)),Ps=(e,n=[])=>(n.push(e),A(e)&&e.args.forEach(e=>Ps(e,n)),n),Rs=e=>e.bnd?e:e.inf?Os(-e.inf):Ms(ze(N("neg",[e.fin])));function Us(e){if(!A(e)||"lim"!==e.op)return null;const[n,t,s,i]=e.args;if(A(t)&&"→"===t.op)return{f:n,v:t.args[0].token,to:t.args[1],side:0};if("sym"===t?.type&&s){const e="r"===i?.token?1:"l"===i?.token?-1:0;return{f:n,v:t.token,to:s,side:e}}return null}function Vs(e){return"sym"!==e.type||"∞"!==e.token&&"oo"!==e.token&&"infinity"!==e.token?"sym"===e.type&&"-∞"===e.token||A(e)&&"neg"===e.op&&"sym"===e.args[0].type&&"∞"===e.args[0].token?Os(-1):Ms(ze(e)):Os(1)}const Ls=new Set(["sin","cos","tan","sec","csc","cot"]),Ws=()=>$("2");function _s(e,n){if(!Hs(n))return[];let t,s;try{const e=Qs(n);t=new Map;s=Xt(je(Js(e,t)))}catch{return[]}const i=[];for(const n of["sin","cos","none"])try{const r="none"===n?jt(s.num):Ys(s.num,t,n),o="none"===n?jt(s.den):Ys(s.den,t,n);if(!r||!o)continue;const a=[Xs(r,o)],u=[Ks(r,t),Ks(o,t)];u[0]&&u[1]&&a.push(Xs(u[0],u[1]));for(const n of a)i.push(ni(e,ei(n,t)))}catch{}return i}const Hs=e=>A(e)&&(Ls.has(e.op)||e.args.some(Hs));function Qs(e){if(!A(e))return e;const n=e.args.map(Qs),[t]=n,s=e=>N("sin",[e]),i=e=>N("cos",[e]),r=e=>A(e)&&"*"===e.op&&O(e.args[0])&&2===Number(e.args[0].value)?2===e.args.length?e.args[1]:N("*",e.args.slice(1)):null;switch(e.op){case"tan":return N("/",[s(t),i(t)]);case"sec":return N("/",[$("1"),i(t)]);case"csc":return N("/",[$("1"),s(t)]);case"cot":return N("/",[i(t),s(t)]);case"sin":{const e=r(t);return e?N("*",[N("*",[Ws(),s(e)]),i(e)]):s(t)}case"cos":{const e=r(t);return e?N("-",[N("^",[i(e),Ws()]),N("^",[s(e),Ws()])]):i(t)}default:return N(e.op,n)}}function Js(e,n){if(!A(e))return e;if(("sin"===e.op||"cos"===e.op)&&!Hs(e.args[0])){const t=e.args[0];n.has(t.s)||n.set(t.s,{u:t,s:`$s${n.size}`,c:`$c${n.size}`});const s=n.get(t.s);return k("sin"===e.op?s.s:s.c)}return N(e.op,e.args.map(e=>Js(e,n)))}function Ys(e,n,t){let s=jt(e);for(const{s:e,c:i}of n.values()){const[n,r]="sin"===t?[e,i]:[i,e],o=Zt(s,n);if(!o)return null;const a=[];for(const[e,t]of o){const s=Math.floor(e/2),i=[t];e%2&&i.push(je(k(n))),s&&i.push(je(N("^",[N("-",[$("1"),N("^",[k(r),Ws()])]),$(String(s))]))),a.push(ge(i))}if(s=jt(de(a)),Ue(s).length>200)return null}return s}function Ks(e,n){let t=jt(e);for(const{u:e,s:s,c:i}of n.values()){const n=N("sin",[N("*",[Ws(),e])]),r=N("cos",[N("*",[Ws(),e])]),o=[];for(const e of Ue(t)){const t=De(e),a=Gs(t,s),u=Gs(t,i);if(a+u===0){o.push(e);continue}if(a+u!==2)return null;const l=us(us(t,s,$("1")),i,$("1")),c=N("/",1===a?[n,Ws()]:2===a?[N("-",[$("1"),r]),Ws()]:[N("+",[$("1"),r]),Ws()]);o.push(je(N("*",[l,c])))}t=jt(de(o))}return t}function Gs(e,n){const t=Zt(je(e),n);return t?Math.max(0,...t.keys()):0}function Xs(e,n){const t=je(N("/",[De(e),De(n)])),s=es(t);return s?Kt(s):De(t)}function ei(e,n){let t=e;for(const{u:e,s:s,c:i}of n.values())t=us(us(t,s,N("sin",[e])),i,N("cos",[e]));return ze(t)}function ni(e,n){const t=e=>{if(!A(e))return e;const n=e.args.map(t);if("/"===e.op&&O(n[0])){const e=n[1],[t,s]=A(e)&&"^"===e.op&&O(e.args[1])?[e.args[0],e.args[1]]:[e,null],i=A(t)&&{cos:"sec",sin:"csc"}[t.op];if(i){const e=N(i,t.args),r=s?N("^",[e,s]):e;return 1===Number(n[0].value)?r:N("*",[n[0],r])}}return N(e.op,n)},s=Mt(ze(t(n)),e.set.view("simplify"),{format:e.format}).node;try{const{num:e,den:n}=Xt(je(s)),t=ze(N("/",[De(e),De(n)]));return t.s.split(" ").length<s.s.split(" ").length?t:s}catch{return s}}const ti=(e,n)=>N("int",[e,"string"==typeof n?k(n):n]);function si(e,n,t,s=0){if(s>6)throw new D("integration went too deep");const i=[],r=e.set.view("integrate"),o=Mt(n,e.set.view("simplify"),{format:e.format});i.push(...o.steps);let a=ze(ti(o.node,t));for(let n=0;n<40;n++){const n=Mt(a,r,{format:e.format});i.push(...n.steps),a=n.node;const t=F(a,"pre").find(({node:e})=>{return A(n=e)&&"int"===n.op&&2===n.args.length;var n});if(!t)return{node:a,steps:i};const o=ii(e,t.node,s);if(!o)throw new D(`no rule for ∫ ${e.format(t.node.args[0])} d${t.node.args[1].token}`);i.push(...o.steps),a=ze(B(a,t.path,o.node))}throw new D("integration did not finish")}function ii(e,n,t){const[s,i]=n.args,r=i.token,o=je(s),a=function(e,n){const{num:t,den:s}=Xt(e),i=Wt(t),r=Wt(s),o=i.coef.div(r.coef);if(o.isOne||!Ft(e,n))return null;const a=ge([...i.factors.map(e=>be(e.base,e.exp)),...r.factors.map(e=>be(e.base,Ne(e.exp)))]);return{c:o,rest:a}}(o,r);if(a){const t=N("*",[De(X(a.c)),ti(De(a.rest),i)]);return{node:t,steps:[e.step("integrate.constant","Take the number out",["split"],n,t,{c:De(X(a.c))})]}}const u=jt(o);if(De(u).s!==s.s&&"add"===u.k){const t=ti(De(u),i);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:s}of F(e,"pre")){if(!A(s))continue;const e="^"===s.op?s.args:"/"===s.op?[s.args[1]]:"der"===s.op||"int"===s.op?[]:1===s.args.length||"root"===s.op?[s.args[s.args.length-1]]:[];for(const s of e){if("sym"===s.type||!Re(s).has(n))continue;const e=Zt(je(s),n);if(!e||1!==Math.max(...e.keys()))continue;const i=e.get(1);Ft(i,n)||se(i)&&i.q.isZero||t.set(s.s,{node:s,a:i})}}for(const s of t.values()){if(!Re(hi(e,s.node,k("§"))).has(n))return s}return null}(s,r);if(l){const i="u"===r?"t":"u",o=hi(s,l.node,k(i));if(!Re(o).has(r)){const s=si(e,ze(o),i,t+1),a=ze(us(s.node,i,l.node)),u=De(Oe(je(a),l.a));return{node:u,steps:[e.step("integrate.substitute","Substitute",["substitute"],n,ze(ti(o,i)),{u:k(i),inside:l.node,a:De(l.a),v:r}),...s.steps,e.step("integrate.back","Substitute back",["substitute"],s.node,u,{u:k(i),inside:l.node})]}}}const c=function(e,n,t,s){const{num:i,den:r}=Xt(t);if(!Ft(r,s))return null;const o=Bt(Zt(i,s)),a=Bt(Zt(r,s));if(!o||!a||a.length<2)return null;const u=je(k(s)),l=e=>Dt(e,s);if(o.length>=a.length){const{q:t,r:i}=Lt(o,a),r=ti(De(de([l(t),Oe(l(i),l(a))])),k(s));return{node:r,steps:[e.step("integrate.divide","Divide the polynomials",["divide"],n,r,{})]}}const{roots:c,rest:f}=Vt(a),p=new Set(c.map(String)).size===c.length,h=3===f.length&&f[1].mul(f[1]).sub(V.of(4).mul(f[0]).mul(f[2])).sign<0;if(!p||1!==f.length&&!h||!c.length&&!h)return null;const d=(e=>e.length<=1?[V.ZERO]:e.slice(1).map((e,n)=>e.mul(V.of(n+1))))(a),m=c.map(e=>Pt(o,e).div(Pt(d,e))),g=c.map((e,n)=>Oe(X(m[n]),de([u,X(e.neg())])));if(!h){const t=ti(De(de(g)),k(s));return{node:t,steps:[e.step("integrate.partial-fractions","Partial fractions",["partial-fractions"],n,t,{})]}}let v=o;c.forEach((e,n)=>{v=pi(v,fi(Lt(a,[e.neg(),V.of(1)]).q,m[n]))});const b=c.reduce((e,n)=>ci(e,[n.neg(),V.of(1)]),[V.of(1)]),{q:w}=Lt(v,b),[y,x]=[w[0]??V.ZERO,w[1]??V.ZERO],[q,$,S]=Lt(a,b).q,M=V.of(4).mul(S).mul(q).sub($.mul($)),O=Dt([q,$,S],s),A=x.div(V.of(2).mul(S)),I=y.sub(x.mul($).div(V.of(2).mul(S))),E=N("sqrt",[ri(M)]),T=N("*",[ri(A),N("ln",[N("abs",[De(O)])])]),j=N("*",[N("/",[N("*",[oi(2),ri(I)]),E]),N("arctan",[N("/",[De(Dt([$,S.mul(V.of(2))],s)),E])])]),z=g.length?ti(De(de(g)),k(s)):oi(0),Z=ze(N("+",[N("+",[z,T]),j]));return{node:Z,steps:[e.step("integrate.complete-square","Complete the square",["partial-fractions"],n,Z,{Q:De(O)})]}}(e,n,o,r);if(c)return c;const f=li(e,n,r);if(f)return f;const p=function(e,n,t,s){if(s>=3)return null;const[i,r]=n.args,o="u"===t?"t":"u",a=new Set;for(const{node:r}of F(i,"pre")){if(r===i||!A(r)||r.s===i.s||a.has(r.s)||!Re(r).has(t)||["der","int"].includes(r.op))continue;let u,l,c;a.add(r.s);try{u=ze(e.differentiate(r,t))}catch{continue}if(O(u)&&0===Number(u.value))continue;try{l=hi(ze(N("/",[i,u])),r,k(o))}catch{continue}if(Re(l).has(t))continue;try{c=si(e,ze(l),o,s+1)}catch{continue}const f=ze(us(c.node,o,r));return{node:f,steps:[e.step("integrate.u-substitution","Substitute",["substitute"],n,ze(ti(l,o)),{u:k(o),inside:r,du:u,v:t}),...c.steps,e.step("integrate.back","Substitute back",["substitute"],c.node,f,{u:k(o),inside:r})]}}return null}(e,n,r,t);return p||function(e,n,t,s,i){if(i>=6)return null;const r=Ve(t),o=r.filter(e=>di(e,s)||!Ft(e,s)),a=r.filter(e=>!o.includes(e));if(1!==a.length)return null;const u=ge(o),l=a[0],c=De(l),f=A(c)?c.op:"",p=["ln","arctan","arcsin","arccos","arcsec","arccsc","arccot"];if(!Ft(u,s)&&!p.includes(f))return null;let h,d,m;p.includes(f)?(h=l,d=u):(h=u,d=l);try{m=si(e,De(d),s,i+1)}catch{return null}const g=je(e.differentiate(De(h),s)),v=ge([h,je(m.node)]),b=ti(De(ge([g,je(m.node)])),k(s)),w=ze(N("-",[De(v),b]));return{node:w,steps:[e.step("integrate.parts","Integration by parts",["parts"],n,w,{u:De(h),dv:De(d),V:m.node,du:De(g),v:s})]}}(e,n,o,r,t)}const ri=e=>De(X(e)),oi=e=>$(String(e));function ai(e,n){if(!e||!Re(e).has(n))return null;const t=Zt(je(e),n);if(!t||1!==Math.max(...t.keys()))return null;const s=t.get(1);return!se(s)||s.q.isZero?null:{a:s.q,node:e}}function ui(e){return A(e)&&"^"===e.op&&O(e.args[1])&&Number.isInteger(Number(e.args[1].value))?{base:e.args[0],n:Number(e.args[1].value)}:{base:e,n:1}}function li(e,n,t){const[s,i]=n.args,r=Ve(je(s)).map(De).map(ui),o=(e,...n)=>A(e.base)&&n.includes(e.base.op),a=(s,i,r,o={})=>({node:r,steps:[e.step(s,i,["rewrite"],n,r,{v:t,...o})]});if(2===r.length&&r.every(e=>1===e.n)){const e=r.find(e=>A(e.base)&&"^"===e.base.op&&"sym"===e.base.args[0].type&&"e"===e.base.args[0].token),n=r.find(e=>o(e,"sin","cos")),s=e&&ai(e.base.args[1],t),i=n&&ai(n.base.args[0],t);if(s&&i){const[t,r]=[s.a,i.a],o=t.mul(t).add(r.mul(r)),[u,l]=[N("sin",[i.node]),N("cos",[i.node])],c="sin"===n.base.op?N("-",[N("*",[ri(t),u]),N("*",[ri(r),l])]):N("+",[N("*",[ri(t),l]),N("*",[ri(r),u])]);return a("integrate.parts-twice","By parts twice",ze(N("/",[N("*",[e.base,c]),ri(o)])),{e:e.base,t:n.base})}}if(2===r.length&&r.every(e=>1===e.n&&o(e,"sin","cos")&&ai(e.base.args[0],t))&&r[0].base.args[0].s!==r[1].base.args[0].s){const[e,n]="sin"===r[0].base.op?r:[r[1],r[0]],[t,s]=[e.base.args[0],n.base.args[0]],o=(e,n)=>N(e,[N(n,[t,s])]);let u;u="sin"===e.base.op&&"cos"===n.base.op?N("+",[o("sin","+"),o("sin","-")]):"cos"===e.base.op?N("+",[o("cos","-"),o("cos","+")]):N("-",[o("cos","-"),o("cos","+")]);return a("integrate.product-to-sum","Product to sum",ze(ti(N("/",[u,oi(2)]),i)))}const u=r.find(e=>o(e,"sin")),l=r.find(e=>o(e,"cos")),c=!u||!l||u.base.args[0].s===l.base.args[0].s;if((u||l)&&c&&r.every(e=>e===u||e===l)&&[u,l].every(e=>!e||e.n>=0))for(const[n,s]of[[l,"sin"],[u,"cos"]]){if(!n||n.n<3||n.n%2==0)continue;const o=n.base.args[0],u=(n.n-1)/2,l=r.filter(e=>e!==n).map(e=>N("^",[e.base,oi(e.n)])),c=[...l,N("^",[N("-",[oi(1),N("^",[N(s,[o]),oi(2)])]),oi(u)]),N(n.base.op,[o])].reduce((e,n)=>N("*",[e,n])),f=ze(ti(c,i)),p=a("integrate.odd-power","An odd power",f,{f:n.base,other:N(s,[o])});if("sym"!==o.type||o.token!==t)return p;const h="u"===t?"t":"u",d=l.length?r.find(e=>e!==n).n:0;if(2*u+d>100)throw new D(`a power this high (${n.n+d}) is not integrated here`);const m="sin"===n.base.op?-1:1,g=N(s,[o]),v=N("*",[N("^",[N("-",[oi(1),N("^",[k(h),oi(2)])]),oi(u)]),N("^",[k(h),oi(d)])]),b=ze(ti(m<0?N("neg",[v]):v,k(h))),w=Zt(jt(je(v)),h);if(!w)return p;const y=[...w].map(([e,n])=>N("*",[De(n),N("/",[N("^",[g,oi(e+1)]),oi(e+1)])])).reduce((e,n)=>N("+",[e,n])),x=ze(m<0?N("neg",[y]):y);return{node:x,steps:[...p.steps,e.step("integrate.u-substitution","Substitute",["substitute"],f,b,{u:k(h),inside:g,du:m<0?N("neg",[n.base]):n.base,v:t}),e.step("integrate.back","Back to "+t,["substitute"],b,x,{u:k(h),inside:g})]}}if(1===r.length&&r[0].n>=3&&o(r[0],"sec","csc")&&"sym"===r[0].base.args[0].type&&r[0].base.args[0].token===t){const{base:e,n:n}=r[0],t=e.args[0],s="sec"===e.op?N("tan",[t]):N("cot",[t]),o=N("/",[N("*",[N("^",[e,oi(n-2)]),s]),oi(n-1)]),u=N("*",[N("/",[oi(n-2),oi(n-1)]),ti(N("^",[e,oi(n-2)]),i)]);return a("integrate.reduction","Reduction formula",ze(N("+",["sec"===e.op?o:N("neg",[o]),u])),{f:e,n:oi(n)})}const f=e=>{if(!A(e)||"sqrt"!==e.op)return null;const n=Zt(je(e.args[0]),t);if(!n||2!==n.size||!n.has(2)||!n.has(0))return null;const[s,i]=[n.get(2),n.get(0)];return!se(s)||!se(i)||s.q.sign>=0||i.q.sign<=0?null:{k:s.q.neg(),c:i.q,root:e}},p=k(t),h=e=>N("sqrt",[ri(e)]),d=f(s),m=A(s)&&"/"===s.op&&O(s.args[0])&&1===s.args[0].value?f(s.args[1]):null;if(d||m){const{k:e,c:n,root:t}=d??m,s=N("arcsin",[N("*",[p,h(e.div(n))])]);return a("integrate.trig-substitution","A trig substitution",ze(d?N("+",[N("/",[N("*",[p,t]),oi(2)]),N("*",[N("/",[ri(n),N("*",[oi(2),h(e)])]),s])]):N("/",[s,h(e)])),{x:p,a:ze(h(n.div(e)))})}return null}const ci=(e,n)=>{const t=Array.from({length:e.length+n.length-1},()=>V.ZERO);return e.forEach((e,s)=>n.forEach((n,i)=>{t[s+i]=t[s+i].add(e.mul(n))})),t},fi=(e,n)=>e.map(e=>e.mul(n)),pi=(e,n)=>Array.from({length:Math.max(e.length,n.length)},(t,s)=>(e[s]??V.ZERO).sub(n[s]??V.ZERO));function hi(e,n,t){return e.s===n.s?t:A(e)?N(e.op,e.args.map(e=>hi(e,n,t))):e}const di=(e,n)=>{const t=Zt(e,n);return Boolean(t)&&[...t.values()].every(e=>!Ft(e,n))&&Math.max(...t.keys())>=1};function mi(e,n,t,s,i,r){if([s,i].some(e=>Vs(e).inf))return function(e,n,t,s,i,r){const o=[s,i].map(e=>Vs(e)),a=e=>e.inf?e.inf*(1/0):ct(e.fin,{digits:20}).number,[u,l]=o.map(a).sort((e,n)=>e-n);for(const n of r?gi(r,t):[]){let s=[];try{s=e.solve(N("=",[n,$("0")]),t,{steps:!1}).solutions}catch{continue}for(const n of s){const s=ct(n,{digits:20});if(Number.isFinite(s.number)&&!s.im&&s.number>u&&s.number<l)throw new D(`the integrand has no value at ${t} = ${e.format(n)}, between the limits: split the integral there`)}}const c=(s,i,r)=>{if(!i.inf)try{const e=ze(us(n,t,s));if(Number.isFinite(ct(e,{digits:15}).number))return e}catch{}const o=e.limit(n,t,s,{steps:!1,side:i.inf?void 0:r});if(!o.exists)throw new D(`the integral diverges: as ${t} → ${e.format(s)}, ${e.format(n)} has no limit (${o.reason})`);if(o.infinite)throw new D(`the integral diverges: as ${t} → ${e.format(s)}, ${e.format(n)} goes to ${o.text}`);return o.result},f=a(o[0])<a(o[1]),[p,h]=[c(s,o[0],f?"right":"left"),c(i,o[1],f?"left":"right")],d=ze(N("-",[h,p])),m=N("-",[h,p]);return{value:d,step:e.step("integrate.improper","Limits at the ends",["evaluate"],n,m,{a:s,b:i,F:n,v:t})}}(e,n,t,s,i,r);if(r&&!Re(s).size&&!Re(i).size){const o=ct(s,{digits:20}).number,a=ct(i,{digits:20}).number,u=[...Re(r)].filter(e=>e!==t);if(!u.length){const[s,i]=o<=a?[o,a]:[a,o];for(const o of gi(r,t)){let r=[];try{r=e.solve(N("=",[o,$("0")]),t,{steps:!1}).solutions}catch{continue}for(const o of r){const r=ct(o,{digits:20});if(!Number.isFinite(r.number)||r.im||r.number<s||r.number>i)continue;if(r.number>s&&r.number<i)throw new D(`the integrand has no value at ${t} = ${e.format(o)}, between the limits, so F(b) - F(a) would be wrong`);let a=NaN;try{a=ct(ze(us(n,t,o)),{digits:15}).number}catch{}if(!Number.isFinite(a))throw new D(`the integral diverges at ${t} = ${e.format(o)}: F has no value at that limit`)}}}for(let e=0;!u.length&&e<=64;e++){const n=o+(a-o)*(e+.5)/65;try{const e=ct(us(r,t,$(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 o=e=>ze(us(n,t,e)),a=ze(N("-",[o(i),o(s)])),u=N("-",[o(i),o(s)]);return{value:a,step:e.step("integrate.evaluate","Between the limits",["evaluate"],n,u,{a:s,b:i,F:n,v:t})}}function gi(e,n){const t=[],s={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};return F(e,"pre").forEach(({node:e})=>{if(!A(e))return;let i=null;"/"===e.op?i=e.args[1]:"^"===e.op&&"num"===e.args[1].type&&e.args[1].value<0||"^"===e.op&&A(e.args[1])&&"neg"===e.args[1].op?i=e.args[0]:s[e.op]&&(i=N(s[e.op],[e.args[0]])),i&&Re(i).has(n)&&!t.some(e=>e.s===i.s)&&t.push(i)}),t}const vi={"=":1,"≠":1,"<":1,">":1,"≤":1,"≥":1,"+":2,"-":2,"±":2,"*":3,"/":3,neg:4,pm:4,"^":5},bi={pi:"π","≤":"≤","≥":"≥"};function wi(e){return $i(e).text}function yi(e,n,t=!1){return e.prec<n||t&&e.prec===n?`(${e.text})`:e.text}const xi=e=>"op"===e.type?e.op:null,qi=e=>e.text.startsWith("-"),ki={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function $i(e){if("num"===e.type)return{text:e.token,prec:e.token.startsWith("-")?4:9};if("sym"===e.type)return{text:bi[e.token]??e.token,prec:9};const n=e.args.map($i),t=vi[e.op];switch(e.op){case"+":case"-":case"±":{const s="+"===e.op&&["+","-"].includes(xi(e.args[1])),i=qi(n[1])?`(${n[1].text})`:s?n[1].text:yi(n[1],t,!0);return{text:`${yi(n[0],t)} ${"±"===e.op?"±":e.op} ${i}`,prec:t}}case"*":{const s=yi(n[0],t),i=qi(n[1])?`(${n[1].text})`:"*"===xi(e.args[1])?n[1].text:yi(n[1],t,!0);return{text:"num"===e.args[0].type&&"num"!==e.args[1].type&&!/^[\d(-]/.test(i)||"sym"===e.args[1].type&&"i"===e.args[1].token&&!/[\dA-Za-z]$/.test(s)?`${s}${i}`:`${s}·${i}`,prec:t}}case"/":return{text:`${yi(n[0],t)}/${yi(n[1],t,!0)}`,prec:t};case"^":return{text:`${yi(n[0],t+1)}^${yi(n[1],t)}`,prec:t};case"neg":return{text:`-${yi(n[0],3)}`,prec:4};case"pm":return{text:`±${yi(n[0],4)}`,prec:4};case"!":return{text:`${yi(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"op"===e.args[1].type&&"="===e.args[1].op?{text:`d/d${n[1].text.split(" = ")[0]} (${n[0].text}) at ${n[1].text}`,prec:1}:{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:`${yi(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:`${ki[e.op][0]}${n.map(e=>e.text).join(", ")}${ki[e.op][1]}`,prec:9};case"&":return{text:`${n[0].text} and ${n[1].text}`,prec:0};default:return void 0!==t?{text:`${yi(n[0],t)} ${e.op} ${yi(n[1],t,!0)}`,prec:t}:{text:`${e.op.replace(/^\\:?/,"")}(${n.map(e=>e.text).join(", ")})`,prec:9}}}const Si=['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-arcsec\n name: Derivative of arcsecant\n mode: differentiate\n pattern: u arcsec v der\n output: u v der u abs u 2 ^ 1 - sqrt * /\n explain: "The derivative of {u}, over the absolute value of {u} times the square root of {u} squared minus 1."\n tags: [chain, trig]\n\n - id: d-arccsc\n name: Derivative of arccosecant\n mode: differentiate\n pattern: u arccsc v der\n output: u v der u abs u 2 ^ 1 - sqrt * / neg\n explain: "Minus the derivative of {u}, over the absolute value of {u} times the square root of {u} squared minus 1."\n tags: [chain, trig]\n\n - id: d-arccot\n name: Derivative of arccotangent\n mode: differentiate\n pattern: u arccot v der\n output: u v der 1 u 2 ^ + / neg\n explain: "Minus 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-sec, name: Integral of sec, mode: integrate, pattern: u sec v 2 int, require: [[sameAs, u, v]], output: v sec v tan + abs ln, tags: [trig], explain: "The derivative of ln|sec {v} + tan {v}| is sec {v}." }\n - { id: i-csc, name: Integral of csc, mode: integrate, pattern: u csc v 2 int, require: [[sameAs, u, v]], output: v csc v cot + abs ln neg, tags: [trig], explain: "The derivative of -ln|csc {v} + cot {v}| is csc {v}." }\n - { id: i-cot, name: Integral of cot, mode: integrate, pattern: u cot v 2 int, require: [[sameAs, u, v]], output: v sin abs ln, tags: [trig], explain: "cot = cos/sin, and ln|sin {v}| differentiates to it." }\n - { id: i-sec-tan, name: Integral of sec·tan, mode: integrate, pattern: u sec u tan * v 2 int, commutative: true, require: [[sameAs, u, v]], output: v sec, tags: [trig], explain: "The derivative of sec {v} is sec {v} tan {v}." }\n - { id: i-csc-cot, name: Integral of csc·cot, mode: integrate, pattern: u csc u cot * v 2 int, commutative: true, require: [[sameAs, u, v]], output: v csc neg, tags: [trig], explain: "The derivative of -csc {v} is csc {v} cot {v}." }\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 # ---- trigonometry: shifts by π/2 and π, written with an unknown angle ----------\n - { id: sin-plus-quarter, name: sin(u + π/2), pattern: u =pi 2 / + sin, commutative: true, output: u cos, tags: [symmetry], explain: "Shifting sine by a quarter turn gives cosine: sin({u} + π/2) = cos {u}." }\n - { id: cos-plus-quarter, name: cos(u + π/2), pattern: u =pi 2 / + cos, commutative: true, output: u sin neg, tags: [symmetry], explain: "cos({u} + π/2) = -sin {u}." }\n - { id: sin-minus-quarter, name: sin(u − π/2), pattern: u =pi 2 / - sin, output: u cos neg, tags: [symmetry], explain: "sin({u} - π/2) = -cos {u}." }\n - { id: cos-minus-quarter, name: cos(u − π/2), pattern: u =pi 2 / - cos, output: u sin, tags: [symmetry], explain: "cos({u} - π/2) = sin {u}." }\n - { id: sin-cofunction, name: sin(π/2 − u), pattern: u neg =pi 2 / + sin, commutative: true, output: u cos, tags: [symmetry], explain: "Sine of the complement is cosine: sin(π/2 - {u}) = cos {u}." }\n - { id: cos-cofunction, name: cos(π/2 − u), pattern: u neg =pi 2 / + cos, commutative: true, output: u sin, tags: [symmetry], explain: "Cosine of the complement is sine: cos(π/2 - {u}) = sin {u}." }\n - { id: tan-cofunction, name: tan(π/2 − u), pattern: u neg =pi 2 / + tan, commutative: true, output: u cot, tags: [symmetry], explain: "tan(π/2 - {u}) = cot {u}." }\n - { id: sin-supplement, name: sin(π − u), pattern: u neg =pi + sin, commutative: true, output: u sin, tags: [symmetry], explain: "sin(π - {u}) = sin {u}." }\n - { id: cos-supplement, name: cos(π − u), pattern: u neg =pi + cos, commutative: true, output: u cos neg, tags: [symmetry], explain: "cos(π - {u}) = -cos {u}." }\n - { id: sin-plus-half, name: sin(u + π), pattern: u =pi + sin, commutative: true, output: u sin neg, tags: [symmetry], explain: "Half a turn changes the sign: sin({u} + π) = -sin {u}." }\n - { id: cos-plus-half, name: cos(u + π), pattern: u =pi + cos, commutative: true, output: u cos neg, tags: [symmetry], explain: "Half a turn changes the sign: cos({u} + π) = -cos {u}." }\n - { id: tan-plus-half, name: tan(u + π), pattern: u =pi + tan, commutative: true, output: u tan, tags: [symmetry], explain: "Tangent repeats every π: tan({u} + π) = tan {u}." }\n - { id: sin-minus-half, name: sin(u − π), pattern: u =pi - sin, output: u sin neg, tags: [symmetry], explain: "sin({u} - π) = -sin {u}." }\n - { id: cos-minus-half, name: cos(u − π), pattern: u =pi - cos, output: u cos neg, tags: [symmetry], explain: "cos({u} - π) = -cos {u}." }\n\n # ---- trigonometry: more exact values (15°, 75°, 22.5°, 67.5°) -------------------\n - { id: sin-pi-12, name: Sine of π/12, pattern: =pi 12 / sin, output: 6 sqrt 2 sqrt - 4 /, tags: [value], explain: "sin(π/12) = sin(π/3 - π/4) = (√6 - √2)/4." }\n - { id: cos-pi-12, name: Cosine of π/12, pattern: =pi 12 / cos, output: 6 sqrt 2 sqrt + 4 /, tags: [value], explain: "cos(π/12) = cos(π/3 - π/4) = (√6 + √2)/4." }\n - { id: tan-pi-12, name: Tangent of π/12, pattern: =pi 12 / tan, output: 2 3 sqrt -, tags: [value], explain: "tan(π/12) = 2 - √3." }\n - { id: sin-5pi-12, name: Sine of 5π/12, pattern: 5 =pi * 12 / sin, output: 6 sqrt 2 sqrt + 4 /, tags: [value], explain: "sin(5π/12) = sin(π/4 + π/6) = (√6 + √2)/4." }\n - { id: cos-5pi-12, name: Cosine of 5π/12, pattern: 5 =pi * 12 / cos, output: 6 sqrt 2 sqrt - 4 /, tags: [value], explain: "cos(5π/12) = cos(π/4 + π/6) = (√6 - √2)/4." }\n - { id: tan-5pi-12, name: Tangent of 5π/12, pattern: 5 =pi * 12 / tan, output: 2 3 sqrt +, tags: [value], explain: "tan(5π/12) = 2 + √3." }\n - { id: sin-pi-8, name: Sine of π/8, pattern: =pi 8 / sin, output: 2 2 sqrt - sqrt 2 /, tags: [value], explain: "By the half-angle formula, sin(π/8) = √(2 - √2)/2." }\n - { id: cos-pi-8, name: Cosine of π/8, pattern: =pi 8 / cos, output: 2 2 sqrt + sqrt 2 /, tags: [value], explain: "By the half-angle formula, cos(π/8) = √(2 + √2)/2." }\n - { id: tan-pi-8, name: Tangent of π/8, pattern: =pi 8 / tan, output: 2 sqrt 1 -, tags: [value], explain: "tan(π/8) = √2 - 1." }\n - { id: sin-3pi-8, name: Sine of 3π/8, pattern: 3 =pi * 8 / sin, output: 2 2 sqrt + sqrt 2 /, tags: [value], explain: "sin(3π/8) = cos(π/8) = √(2 + √2)/2." }\n - { id: cos-3pi-8, name: Cosine of 3π/8, pattern: 3 =pi * 8 / cos, output: 2 2 sqrt - sqrt 2 /, tags: [value], explain: "cos(3π/8) = sin(π/8) = √(2 - √2)/2." }\n - { id: tan-3pi-8, name: Tangent of 3π/8, pattern: 3 =pi * 8 / tan, output: 2 sqrt 1 +, tags: [value], explain: "tan(3π/8) = √2 + 1." }\n\n # ---- trigonometry: a function of an inverse function (a right triangle) -----------\n - { id: sin-arccos, name: sin(arccos u), pattern: u arccos sin, output: u 2 ^ neg 1 + sqrt, tags: [inverse], explain: "In a right triangle with cos θ = {u}, the other side is √(1 - {u}²): sin(arccos {u}) = √(1 - {u}²)." }\n - { id: cos-arcsin, name: cos(arcsin u), pattern: u arcsin cos, output: u 2 ^ neg 1 + sqrt, tags: [inverse], explain: "In a right triangle with sin θ = {u}, cos θ = √(1 - {u}²)." }\n - { id: tan-arcsin, name: tan(arcsin u), pattern: u arcsin tan, output: u u 2 ^ neg 1 + sqrt /, tags: [inverse], explain: "tan(arcsin {u}) = {u}/√(1 - {u}²)." }\n - { id: tan-arccos, name: tan(arccos u), pattern: u arccos tan, output: u 2 ^ neg 1 + sqrt u /, tags: [inverse], explain: "tan(arccos {u}) = √(1 - {u}²)/{u}." }\n - { id: sin-arctan, name: sin(arctan u), pattern: u arctan sin, output: u u 2 ^ 1 + sqrt /, tags: [inverse], explain: "In a right triangle with tan θ = {u}, the long side is √(1 + {u}²): sin(arctan {u}) = {u}/√(1 + {u}²)." }\n - { id: cos-arctan, name: cos(arctan u), pattern: u arctan cos, output: 1 u 2 ^ 1 + sqrt /, tags: [inverse], explain: "cos(arctan {u}) = 1/√(1 + {u}²)." }\n - { id: sec-arctan, name: sec(arctan u), pattern: u arctan sec, output: u 2 ^ 1 + sqrt, tags: [inverse], explain: "sec(arctan {u}) = √(1 + {u}²)." }\n - { id: cos-arcsec, name: cos(arcsec u), pattern: u arcsec cos, output: 1 u /, tags: [inverse], explain: "arcsec {u} is the angle whose cosine is 1/{u}." }\n - { id: sin-arccsc, name: sin(arccsc u), pattern: u arccsc sin, output: 1 u /, tags: [inverse], explain: "arccsc {u} is the angle whose sine is 1/{u}." }\n - { id: tan-arccot, name: tan(arccot u), pattern: u arccot tan, output: 1 u /, tags: [inverse], explain: "arccot {u} is the angle whose tangent is 1/{u}." }\n\n # ---- trigonometry: the angle-sum formulas, read backward -------------------------\n - { id: sin-sum, name: sin(u + v), pattern: u sin v cos * u cos v sin * +, commutative: true, output: u v + sin, tags: [identity], explain: "sin {u} cos {v} + cos {u} sin {v} = sin({u} + {v})." }\n - { id: sin-difference, name: sin(u − v), pattern: u sin v cos * u cos v sin * -, commutative: true, output: u v - sin, tags: [identity], explain: "sin {u} cos {v} - cos {u} sin {v} = sin({u} - {v})." }\n - { id: sin-difference-led-by-minus, name: sin(u − v), pattern: u cos v sin * neg u sin v cos * +, commutative: true, output: u v - sin, tags: [identity], explain: "sin {u} cos {v} - cos {u} sin {v} = sin({u} - {v})." }\n - { id: cos-sum, name: cos(u + v), pattern: u cos v cos * u sin v sin * -, commutative: true, output: u v + cos, tags: [identity], explain: "cos {u} cos {v} - sin {u} sin {v} = cos({u} + {v})." }\n - { id: cos-difference, name: cos(u − v), pattern: u cos v cos * u sin v sin * +, commutative: true, output: u v - cos, tags: [identity], explain: "cos {u} cos {v} + sin {u} sin {v} = cos({u} - {v})." }\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'],Mi=['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'],Ni=new Set(["<",">","≤","≥"]),Oi=new Set(["sin","cos","tan","sec","csc","cot"]),Ai=new Set(["arcsin","arccos","arctan","arcsec","arccsc","arccot"]),Ii={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: {canceled}.","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.","simplify.trig":"Write it with sin and cos, use sin² + cos² = 1 and the double-angle formulas, and cancel.","limit.substitute":"{f} is continuous at {v} = {a}: put {a} in.","limit.cancel":"{f} is 0/0 at {v} = {a}: cancel the common factor first.","limit.lhopital":"{f} is {form} as {v} → {a}: by L'Hôpital's rule, take the limit of the top's derivative over the bottom's.","limit.leading":"As {v} → {a}, the highest powers decide: {f} behaves like {lead}.","limit.zero-times-infinity":"{f} is 0·∞: write it as a quotient.","limit.combine":"{f} is ∞ − ∞: write it as one fraction.","limit.squeeze":"{bounded} stays between two bounds, and what it is multiplied by goes to 0: so does the product (the squeeze theorem).","limit.divide-power":"Divide the top and the bottom by {power}.","limit.conjugate":"{f} is ∞ − ∞ with a root: multiply top and bottom by the conjugate.","limit.exp-log":"{f} is {form}: write it as e to the power (exponent · ln base), and find the limit of the exponent.","limit.one-sided":"From the left {f} goes to {left}, from the right to {right}: the limit does not exist.","solve.sign-chart":"Where each side minus the other is 0, or has no value: {points}. It keeps one sign between them, so test one {v} in each interval, and each point.","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.","integrate.improper":"An improper integral: at an infinite end, the limit of {F} as {v} goes there; then subtract.","integrate.u-substitution":"Let {u} = {inside}, so d{u} = {du} d{v}: the integral is in {u} alone.","integrate.complete-square":"Partial fractions, and complete the square in {Q}: the top that is a multiple of its derivative gives a log, the rest an arctangent.","integrate.parts-twice":"By parts twice: the integral of {e}·{t} comes back, so solve for it.","integrate.product-to-sum":"Write the product of sines and cosines as a sum.","integrate.odd-power":"Keep one {f} and write the rest with {other} (sin² + cos² = 1): then {other} is the substitution.","integrate.reduction":"The reduction formula for {f} to the power {n}.","integrate.trig-substitution":"Let {x} = {a}·sin θ: the root becomes {a}·cos θ.",substitute:"Put in the values."},Ei=["normal","rewrite","simplify","expand","factor","cancel","diff","differentiate","integrate","solve","solveSystem","substitute","approximate","equivalent","limit"];class Ti{constructor(e,n,t,s,i){this.set=e,this.messages=n,this.format=t,this.read=s,this.complex=i;for(const e of Ei){const n=Ti.prototype[e];this[e]=(...e)=>Y(i,()=>n.apply(this,e))}}node(e){return this.atPoints(this.read_(e))}read_(e){if(e&&"object"==typeof e&&!Array.isArray(e)&&e.type)return e;if(Array.isArray(e))return E(e);if("string"!=typeof e)throw new D("expected an expression");if(this.read){const n=this.read(e);return Array.isArray(n)?E(n):"string"==typeof n?I(n):n}return I(e)}atPoints(e){if(!e||!A(e)||!e.s.includes("= der"))return e;const n=e.args.map(e=>this.atPoints(e)),[t,s]=n;if("der"===e.op&&A(s)&&"="===s.op&&"sym"===s.args[0].type){const e=s.args[0].token;return this.substitute(this.diff(t,e).result,{[e]:s.args[1].s}).result}return N(e.op,n)}step(e,n,t,s,i,r={}){return function(e,n,t,s,i,r,o,a,u=[]){const l=(r??"").replace(/\{(\w+)\}/g,(e,n)=>{const t=o?.[n];return void 0===t?e:"string"==typeof t?t:a(t)});return{id:e,name:n,tags:t,from:s.s,to:i.s,path:u,before:s.s,after:i.s,explanation:l}}(e,n,t,s,i,this.messages[e]??"",r,this.format)}result(e,n,t,s={}){let i=e;if(t.approximate&&i){i=ht(i,{digits:"number"==typeof t.approximate?t.approximate:15})}return{result:i,text:i?this.format(i):"",steps:It(n,At(t.steps)),...s}}variable(e,n){if(n&&!/^\\?[A-Za-z\u0370-\u03FF][A-Za-z0-9_\u0370-\u03FF′]*$/.test(n))throw new D(`"${n}" is not a variable name; for a derivative at a point write der(f, x = a)`);if(n)return n;const t=[...Re(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 ze(this.node(e))}rewrite(e,n,t={}){const s=this.node(e),i=this.set.view(n);if(!i.size)throw new D(`no rules in mode "${n}" (modes: ${this.set.modes().join(", ")})`);const r=Mt(s,i,{format:this.format,order:t.order,variable:t.variable});return this.result(r.node,[...this.tidyStep(s,ze(s)),...r.steps],t)}simplify(e,n={}){const t=this.node(e),s=[...this.tidyStep(t,ze(t))],i=Mt(t,this.set.view("simplify"),{format:this.format});s.push(...i.steps);let r=i.node,o=null;const a=je(r),u=[],l=0===Re(r).size,c=l?null:es(a);c&&u.push({node:Kt(c),id:"simplify.cancel",name:"Cancel"});const f=Mt(De(jt(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:Kt(Wt(a)),id:"simplify.factor",name:"Factor"});const p=e=>F(e,"pre").some(({node:e})=>A(e)&&Oi.has(e.op)&&F(e.args[0],"pre").some(({node:e})=>A(e)&&Ai.has(e.op)));for(const e of _s(this,r))u.push({node:e,id:"simplify.trig",name:"Trigonometric identities",prefer:p(r)&&!p(e)});let h=!1;for(const e of u)h&&"simplify.trig"===e.id&&!e.prefer||(e.prefer&&(h=!0),(j(e.node)<j(r)||e.prefer)&&(o=this.step(e.id,e.name,["shorter"],r,e.node),r=e.node));return o&&s.push(o),this.result(r,s,n)}expand(e,n={}){const t=this.node(e),s=De(jt(je(t)));return this.result(s,t.s===s.s?[]:[this.step("expand","Multiply out",["expand"],t,s)],n)}factor(e,n={}){const t=this.node(e),s=Wt(je(t)),i=Kt(s),r=[],o=s.notes.find(e=>"factor.common"===e.id);return i.s!==ze(t).s&&r.push(this.step(o?"factor.common":"factor","Factor",["factor"],t,i,o?{common:De(o.values.common)}:{})),this.result(i,r,n)}cancel(e,n={}){const t=this.node(e),s=je(t),i=es(s);if(!i)return this.result(ze(t),this.tidyStep(t,ze(t)),n);const r=Kt(i),o=Xt(s),a=N("/",[De(o.num),De(o.den)]),u=[];return"/"===t.op&&a.s===ze(t).s||u.push(this.step("together","One fraction",["together"],t,a)),r.s!==a.s&&u.push(this.step("cancel","Cancel",["cancel"],a,r,{canceled:i.canceled.length?i.canceled.map(e=>this.format(De(e))).join(", "):"numbers"})),this.result(r,u,n)}diff(e,n,t={}){const s=this.node(e),i=this.variable(s,n);let r=s;const o=[];for(let e=0;e<(t.order??1);e++){const e=Mt(N("der",[r,k(i)]),this.set.view("differentiate"),{format:this.format,order:"pre"}),n=Mt(e.node,this.set.view("simplify"),{format:this.format});o.push(...e.steps,...n.steps),r=n.node}return this.result(r,o,t,{variable:i})}differentiate(e,n){const t=Mt(N("der",[e,k(n)]),this.set.view("differentiate"),{format:this.format,order:"pre"});return Mt(t.node,this.set.view("simplify"),{format:this.format}).node}integrate(e,n,t={}){let s=this.node(e);const i=e=>void 0===e?null:this.node("number"==typeof e?String(e):e);let r=i(t.from),o=i(t.to);if(A(s)&&"int"===s.op){const[e,t,i,a]=s.args;n=t.token,i&&a&&(r=i,o=a),s=e}const a=this.variable(s,n),u=si(this,s,a),l=Mt(u.node,this.set.view("simplify"),{format:this.format}),c=[...u.steps,...l.steps];if(r&&o){const e=mi(this,l.node,a,r,o,s);c.push(e.step);const n=Mt(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=N("+",[f,k(String(t.constant))])),this.result(f,c,t,{variable:a})}solve(e,n,t={}){const s=this.node(e),i=this.variable(s,n);if(A(s)&&Ni.has(s.op))return this.inequality(s,i,t);const r=is(this,s,i,t);let o=r.solutions;if(t.approximate){const e="number"==typeof t.approximate?t.approximate:15;o=o.map(n=>ht(n,{digits:e}))}const a=o.map(e=>N("=",[k(i),e])),u=a.length?a.reduce((e,n)=>e?N("|",[e,n]):n,null):null;return{solutions:o,result:u,variable:i,text:r.always?`true for every ${i}`:u?this.format(u):r.unsolved.length?`no exact solution found for ${i}`:"no solution",unsolved:r.unsolved.filter(e=>!e.always),always:r.always,steps:It(r.steps,At(t.steps))}}inequality(e,n,t){const s=ks(this,e,n),i={solutions:[],variable:n,unsolved:[],always:!1,steps:It(s.steps,At(t.steps))};if(!s.pieces)return{...i,pieces:null,intervals:"",result:null,unsolved:[e],text:`no exact solution found for ${n}`};const r=k(n),o=1===s.pieces.length&&!s.pieces[0].lo&&!s.pieces[0].hi,a=s.pieces.map(({lo:e,hi:n,loClosed:t,hiClosed:s})=>e&&n&&e.s===n.s?N("=",[r,e]):e||n?e?n?N(s?"≤":"<",[N(t?"≤":"<",[e,r]),n]):N(t?"≥":">",[r,e]):N(s?"≤":"<",[r,n]):null).filter(Boolean).reduce((e,n)=>e?N("|",[e,n]):n,null),u=s.pieces.length?s.pieces.map(({lo:e,hi:n,loClosed:t,hiClosed:s})=>e&&n&&e.s===n.s?`{${this.format(e)}}`:`${t?"[":"("}${e?this.format(e):"-∞"}, ${n?this.format(n):"∞"}${s?"]":")"}`).join(" ∪ "):"∅",l=o?`true for every ${n}`:a?this.format(a):"no solution";return{...i,pieces:s.pieces,intervals:u,result:a,always:o,text:l}}limit(e,n,t,s={}){null==t||"object"!=typeof t||Array.isArray(t)||t.type||(s=t,t=void 0);const i=this.node(e),r=Us(i);if(!r&&F(i,"pre").some(({node:e})=>Us(e))){let e=i;for(const{node:n,path:t}of F(i,"post").filter(({node:e})=>Us(e)).reverse()){const s=this.limit(n,void 0,void 0,{steps:!1});if(!s.exists)return s;if(s.infinite)throw new D("a limit inside an expression that is infinite is not worked out here");e=B(e,t,s.result)}return{...this.simplify(e,s),exists:!0,infinite:!1}}const o=r?r.f:i,a=r?r.v:this.variable(i,n),u=r?r.to:"number"==typeof t?$(String(t)):this.node(t??"0"),l="right"===s.side||"+"===s.side?1:"left"===s.side||"-"===s.side?-1:r?r.side:0;try{const{value:e,steps:n}=Bs(this,o,a,Vs(u),l);return{...this.result((c=e,c.inf?c.inf>0?As:k("-∞"):c.fin),n,s),exists:!0,infinite:Boolean(e.inf)}}catch(e){if(!(e instanceof Ss))throw e;return{result:null,text:"does not exist",exists:!1,reason:e.message,steps:[]}}var c}solveSystem(e,n,t={}){const s=e.map(e=>this.node(e)),i=n??[...new Set(s.flatMap(e=>[...Re(e)]))].sort(),r=function(e,n,t){const s=[],i=n.map(n=>{const s=ss(n)?de([je(n.args[0]),Ne(je(n.args[1]))]):je(n),i=t.map(n=>{const t=Zt(s,n);if(!t||Math.max(0,...t.keys())>1)throw new D(`not linear in ${n}`);const i=t.get(1)??X(V.ZERO);if(!se(i))throw new D(`the coefficient of ${n} must be a number (it is ${e.format(De(i))})`);return i.q});let r=s;for(let e=0;e<t.length;e++)r=de([r,ge([X(i[e].neg()),je(k(t[e]))])]);for(const e of t)if(Ft(r,e))throw new D(`not linear in ${e}`);return{coeffs:i,rhs:Ne(r)}}),r=()=>i.map(e=>ns(De(de(e.coeffs.map((e,n)=>ge([X(e),je(k(t[n]))])))),De(e.rhs))).reduce((e,n)=>e?N("&",[e,n]):n,null);let o=0;const a=[];for(let n=0;n<t.length&&o<i.length;n++){const u=i.findIndex((e,t)=>t>=o&&!e.coeffs[n].isZero);if(u<0)continue;[i[o],i[u]]=[i[u],i[o]];const l=r(),c=i[o],f=c.coeffs[n];c.coeffs=c.coeffs.map(e=>e.div(f)),c.rhs=ge([X(f.inv()),c.rhs]);for(let e=0;e<i.length;e++){if(e===o||i[e].coeffs[n].isZero)continue;const t=i[e].coeffs[n];i[e].coeffs=i[e].coeffs.map((e,n)=>e.sub(t.mul(c.coeffs[n]))),i[e].rhs=de([i[e].rhs,ge([X(t.neg()),c.rhs])])}s.push(e.step("system.eliminate","Eliminate",["eliminate"],l,r(),{v:k(t[n])})),a.push(n),o++}for(const e of i.slice(o))if(!se(e.rhs)||!e.rhs.q.isZero)return{solution:null,steps:s,status:"none"};if(a.length<t.length)return{solution:null,steps:s,status:"many"};const u=new Map;return a.forEach((e,n)=>u.set(t[e],De(i[n].rhs))),{solution:u,steps:s,status:"one"}}(this,s,i),o=r.solution?Object.fromEntries([...r.solution].map(([e,n])=>[e,n])):null,a="one"===r.status?i.map(e=>`${e} = ${this.format(o[e])}`).join(", "):"none"===r.status?"no solution":"infinitely many solutions";return{solution:o,status:r.status,text:a,steps:It(r.steps,At(t.steps))}}substitute(e,n,t={}){const s=this.node(e);let i=s;for(const[e,t]of Object.entries(n))i=us(i,e,"number"==typeof t?this.node(String(t)):this.node(t));const r=this.simplify(i,t),o=[this.step("substitute","Substitute",["substitute"],s,i)];return{...r,steps:[...It(o,At(t.steps)),...r.steps]}}defined(e){const n=this.set.view("define");return n.size?Mt(e,n,{format:this.format}).node:e}approximate(e,n={}){const t=this.defined(this.node(e));if(Re(t).size&&!n.scope){const e=ht(ze(t),n);return{result:e,text:this.format(e),number:null,exact:!1}}const s=ct(t,n);return{result:s.node,text:s.text,number:s.number,re:s.re,im:s.im,exact:s.exact}}equivalent(e,n){const t=this.node(e),s=this.node(n),i=this.defined(N("-",[t,s])),r=this.simplify(i,{steps:!1}).result;if("num"===r.type&&"0"===r.token)return{equal:!0,how:"exact"};const o=[...Re(i)];if(!o.length)try{return{equal:Math.abs(ct(i,{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(o.map((n,t)=>[n,String(a[(e+t)%a.length]+t/7)]));let t;try{t=ct(i,{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 ji(e={}){const n=!1===e.defaults?[]:[...Si,...e.complex?Mi:[]],{specs:t,messages:s}=function(e){yt();const n=[],t={};for(const s of e){const e="string"==typeof s?xn(s):s,i=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");d(n.symbol)||f({symbol:String(n.symbol),arity:"any"===n.arity?u:Number(n.arity),label:n.label})}Object.assign(t,(Array.isArray(e)?null:e?.messages)??{});for(const e of i)n.push(e)}return{specs:n,messages:t}}([...n,...e.rules??[]]),i=Y(e.complex,()=>xt(t));return new Ti(i,{...Ii,...s},e.format??wi,e.read??null,Boolean(e.complex))}const zi=Symbol.for("inlinemath.expressions"),Zi=new Map,Fi={re:"Re",im:"Im",conj:"overline"},Bi=["Re","Im","re","im","conj","arg"];function Di(e){const t=[],s=e=>{"op"===e.type?(e.args.forEach(s),n(e.op)?(-1===n(e.op).arity&&t.push(String(e.args.length)),t.push(e.op)):t.push(String(e.args.length),`\\:${Fi[e.op]??e.op}`)):t.push(e.token)};return s(e),t}function Ci(n,i){if(!i)return n;const r=new Map;for(const[n,t]of Object.entries(i))if("number"==typeof t?Number.isFinite(t):"bigint"==typeof t||"string"==typeof t)try{r.set(n,e(String(t)))}catch{}if(!r.size)return n;const o=function(e){let n;try{n=t(e)}catch{return new Set}const i=e=>"symbol"===e?.type?e.value:"op"===e?.type&&["=","→"].includes(e.op)&&"symbol"===e.args[0].type?e.args[0].value:null,r=new Set;return s(n,e=>{if("op"!==e.type||e.args.length<2)return;const n=e.op.startsWith("\\:")?e.op.slice(2):e.op;["der","int","lim","diff","derivative","differentiate","integrate","integral","solve","limit"].includes(n)&&i(e.args[1])&&r.add(i(e.args[1]))}),r}(n);return n.flatMap(e=>r.has(e)&&!o.has(e)?r.get(e):[e])}const Pi={right:"right",r:"right","+":"right",left:"left",l:"left","-":"left"},Ri=new Set(["simplify","expand","factor","cancel","diff","integrate","solve","approx","limit"]),Ui={integral:"integrate",differentiate:"diff",approximate:"approx",simp:"simplify"};function Vi(n={}){const t=n.rules||n.names?null:n.complex?"complex":"default";if(t&&Zi.has(t))return Zi.get(t);const s=[...n.names??[],...n.complex?Bi:[],...Ri,...Object.keys(Ui)],i=ji({...n,read:n=>e(n,{names:s}),format:wi});return t&&Zi.set(t,i),i}function Li(e={}){const n=e.cas??Vi(),t=void 0===e.steps?{}:{steps:e.steps},s=(e,o)=>{let a;try{a=n.read(e)}catch{return i(e,o)}const u=o&&o[zi];u&&(a=a.flatMap(e=>Object.hasOwn(u,e)?u[e]:[e])),a=Ci(a,o);const l=a[a.length-1],c=l?.startsWith("\\:")?Ui[l.slice(2)]??l.slice(2):null,f=c&&Ri.has(c),p="der"===l||"int"===l||"lim"===l;if(!f&&!p)return i(e,o);const h=n.node(a),d=p&&h.op!==l,m=f?h.args:[h],g=e=>e?e.s:void 0,v=(e,s,i)=>{if(!s||"="!==s.op)return n.diff(e,g(s),{...t,order:i});const r=s.args[0].s,o=n.diff(e,r,{...t,order:i}),a=n.substitute(o.result,{[r]:s.args[1].s},t);return{...a,steps:[...o.steps??[],...a.steps??[]]}};let b;try{switch(d?"simplify-read":f?c:"der"===l?"derivative":"lim"===l?"lim":"antiderivative"){case"simplify-read":b=n.simplify(h,t);break;case"simplify":b=n.simplify(m[0],t);break;case"expand":b=n.expand(m[0],t);break;case"factor":b=n.factor(m[0],t);break;case"cancel":b=n.cancel(m[0],t);break;case"diff":b=v(m[0],m[1],m[2]?Number(m[2].s):1);break;case"integrate":b=n.integrate(m[0],g(m[1]),{...t,...m[3]?{from:m[2].s,to:m[3].s}:{}});break;case"solve":b=n.solve(m[0],g(m[1]),t);break;case"lim":b=n.limit(h,void 0,void 0,t);break;case"limit":b=(([e,s,i,r])=>{let o=r?Pi[r.s.replace(/^\\/,"")]:void 0;if(r&&!o)throw new Error(`a side is right or left, not ${r.s}`);if(s&&"→"===s.op){[s,i]=s.args;const e="^"===i.op?i.args[1].s.replace(/^\\/,""):null;"+"!==e&&"-"!==e||(o=Pi[e],i=i.args[0])}return n.limit(e,g(s),i,{...t,...o?{side:o}:{}})})(m);break;case"approx":b=n.approximate(m[0],{...t,digits:m[1]?Number(m[1].s):15});break;case"derivative":b=v(h.args[0],h.args[1],1);break;default:b=n.integrate(h,void 0,t)}}catch(n){return`(${e})`}if(s.last=b,!b.result)return`"${b.text}"`;const w=r(Di(b.result));return/^-?\d+(\.\d+)?$/.test(w)?w:`(${w})`};return s}const Wi=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function _i(e,n={}){return`<ol class="mv-steps">${e.map(e=>{const t=Di(I(e.from)),s=o(t,{...n,highlight:e.path&&e.path.length?{path:e.path}:void 0}),i=e.to===e.from?"":`<span class="mv-step-arrow" aria-label="becomes">⟶</span>${o(Di(I(e.to)),n)}`,r=e.explanation?`<p class="mv-step-why">${Wi(e.explanation)}</p>`:"";return`<li class="mv-step" data-rule="${Wi(e.id)}"><span class="mv-step-name">${Wi(e.name)}</span><div class="mv-step-maths">${s}${i}</div>${r}</li>`}).join("")}</ol>`}export{Li as casBlocks,Vi as mathCAS,_i as stepsHTML,Di as tokensOf};
1
+ /* Inline Math 0.4.2 — MIT license; MathZetta not included: map mathzetta, mathzetta/speech and mathzetta/calculate (and mathzetta/text, for cas.external.js) with an import map */
2
+ import{parse as e,operator as n,fromPostfix as t,walk as s}from"mathzetta";import"mathzetta/speech";import{calculateBlock as i}from"mathzetta/calculate";import{toText as r}from"mathzetta/text";import{a as o}from"./chunks/html-ItSMWpG6.js";import"./chunks/draw-BlziYtHI.js";const a=new Map,u=-1,l="\\:",c=e=>"string"==typeof e&&e.startsWith(l)&&e.length>2;function f(e){if(!e||!e.symbol)throw new Error("operator needs a symbol");if(!Number.isInteger(e.arity)||e.arity<0&&e.arity!==u)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 a.set(n.symbol,n),n}const p=Object.freeze({symbol:l,arity:u,commutative:!1,fold:null,label:"function"});function h(e){const n=a.get(e);return n||(c(e)?{...p,symbol:e,label:e.slice(2)}:null)}function d(e){return a.has(e)||c(e)}const m=e=>Number.isFinite(e)&&Number.isInteger(e)?e:null,g=e=>Number.isFinite(e)?e:null;!function(){f({symbol:"+",arity:2,commutative:!0,label:"add",fold:(e,n)=>g(e+n)}),f({symbol:"-",arity:2,label:"subtract",fold:(e,n)=>g(e-n)}),f({symbol:"*",arity:2,commutative:!0,label:"multiply",fold:(e,n)=>g(e*n)}),f({symbol:"/",arity:2,label:"divide",fold:(e,n)=>0===n?null:m(e/n)}),f({symbol:"^",arity:2,label:"power",fold:(e,n)=>Number.isInteger(n)&&Math.abs(n)<=64?g(e**n):null}),f({symbol:"neg",arity:1,label:"negate",fold:e=>g(-e)}),f({symbol:"pm",arity:1,label:"plus or minus"}),f({symbol:"±",arity:2,label:"plus or minus"}),f({symbol:"mod",arity:2,label:"modulo",fold:(e,n)=>0===n?null:m((e%n+n)%n)}),f({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}),f({symbol:"_",arity:2,label:"subscript"}),f({symbol:"der",arity:2,label:"derivative"}),f({symbol:"evaluated",arity:4,label:"evaluated from a to b"}),f({symbol:"setbuilder",arity:2,label:"the set of … such that"}),f({symbol:"int",arity:u,label:"integral"}),f({symbol:"lim",arity:u,label:"limit"}),f({symbol:"\\sumidx",arity:u,label:"sum over an index"}),f({symbol:"\\prodidx",arity:u,label:"product over an index"}),f({symbol:"abs",arity:1,label:"absolute value",fold:e=>g(Math.abs(e))}),f({symbol:"floor",arity:1,label:"floor",fold:e=>g(Math.floor(e))}),f({symbol:"ceil",arity:1,label:"ceiling",fold:e=>g(Math.ceil(e))}),f({symbol:"round",arity:2,label:"round",fold:(e,n)=>Number.isInteger(n)?g(Math.round(e*10**n)/10**n):null}),f({symbol:"fixed",arity:2,label:"fixed",fold:()=>null}),f({symbol:"sqrt",arity:1,label:"square root",fold:e=>m(Math.sqrt(e))}),f({symbol:"root",arity:2,label:"nth root",fold:(e,n)=>m(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","arcsec","arccsc","arccot","arcsinh","arccosh","arctanh","ln","loglog","logloglog","expm1"])f({symbol:e,arity:1,label:e});f({symbol:"log",arity:2,label:"log to a base"}),f({symbol:"atan2",arity:2,label:"atan2"}),f({symbol:"perm",arity:2,label:"permutations"}),f({symbol:"comb",arity:2,label:"combinations"}),f({symbol:"random",arity:0,label:"random"});for(const e of["max","min","gcd","mean","sum","prod"])f({symbol:e,arity:u,label:e});for(const e of["()","[]","{}","(]","[)"])f({symbol:e,arity:u,label:"group"});for(const e of["pmatrix","bmatrix","vmatrix"])f({symbol:e,arity:u,label:"matrix"});f({symbol:"det",arity:1,label:"determinant"});for(const e of["=","===","≠","≠=","<",">","≤","≥","∈","∉","∪","∩","≈","≡","→","pmod","&","|","\\xor","\\nand","\\nor","\\implies","\\iff"])f({symbol:e,arity:2,label:e});f({symbol:"\\not",arity:1,label:"not"}),f({symbol:"?:",arity:3,label:"if then else"})}();const v="num",b="sym",w="op",y=Object.freeze([]);class x extends Error{constructor(e){super(e),this.name="ExprError"}}function q(e){if("number"!=typeof e||!Number.isFinite(e))throw new x(`not a finite number: ${e}`);const n=(t=e,Object.is(t,-0)?"0":String(t));var t;return Object.freeze({type:v,token:n,value:e,args:y,s:n})}function k(e){if("string"!=typeof e||""===e)throw new x("symbol needs a non-empty token");return Object.freeze({type:b,token:e,value:null,args:y,s:e})}function $(e){const n=/^(-?)0*(\d+?)(?:\.(\d*?)0*)?$/.exec(String(e));if(!n)throw new x(`not an exact decimal: ${e}`);const[,t,s,i=""]=n,r=i?`${s}.${i}`:s,o=/^0(\.0*)?$/.test(r)?"0":t+r;return Object.freeze({type:v,token:o,value:Number(o),args:y,s:o})}const S=/^-?\d+(\.\d+)?$/;function M(e){const n=String(e);if(S.test(n))return $(n);if(""!==n&&!/\s/.test(n)){const e=Number(n);if(Number.isFinite(e))return q(e)}return k(n)}function N(e,n){const t=h(e);if(!t)throw new x(`unknown operator "${e}"`);if(t.arity!==u&&n.length!==t.arity)throw new x(`"${e}" takes ${t.arity} operand(s), got ${n.length}`);const s=Object.freeze(n.slice()),i=t.arity===u?` ${s.length}`:"",r=`${s.length?s.map(e=>e.s).join(" "):""}${s.length,""}${i} ${e}`.trimStart();return Object.freeze({type:w,op:e,token:e,value:null,args:s,s:r})}const O=e=>e.type===v,I=e=>e.type===w;function A(e){return E(function(e){const n=String(e).trim();return""===n?[]:n.split(/\s+/)}(e))}function E(e){if(!Array.isArray(e))throw new x("fromPostfix needs an array of tokens");if(0===e.length)throw new x("empty expression");const n=[];for(let t=0;t<e.length;t++){const s=String(e[t]);if(d(s)){let e=h(s).arity;if(e===u){const i=n.pop();if(e=i&&i.type===v&&Number.isInteger(i.value)&&i.value>=0?i.value:-1,e<0)throw new x(`"${s}" at position ${t+1} takes any number of operands, so a count must come before it`)}if(n.length<e)throw new x(`"${s}" at position ${t+1} needs ${e} operand(s), only ${n.length} on the stack`);const i=n.splice(n.length-e,e);n.push(N(s,i))}else n.push(M(s))}if(1!==n.length){const t=[...new Set(e.filter(e=>!d(e)))];throw new x(`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 T(e){if(e.type!==w)return 0;let n=0;for(const t of e.args)n=Math.max(n,T(t));return n+1}function j(e){if(e.type!==w)return 1;let n=1;for(const t of e.args)n+=j(t);return n}function z(e,n=[]){if(e.type!==w)n.push(e.token);else for(const t of e.args)z(t,n);return n}function Z(e){return e.type===v||e.type!==b&&e.args.every(Z)}function C(e,n="pre",t=[],s=[]){"pre"===n&&s.push({node:e,path:t});for(let i=0;i<e.args.length;i++)C(e.args[i],n,t.concat(i),s);return"post"===n&&s.push({node:e,path:t}),s}function F(e,n){let t=e;for(const e of n){if(!t.args[e])throw new x(`bad path [${n.join(",")}]`);t=t.args[e]}return t}function B(e,n,t){if(0===n.length)return t;const[s,...i]=n,r=e.args.slice();return r[s]=B(r[s],i,t),N(e.op,r)}class D extends Error{constructor(e){super(e),this.name="CasError"}}const W=1e5,R=e=>e<0n?-e:e,P=e=>0n===e?0:R(e).toString(2).length;function U(e,n){for(e=R(e),n=R(n);n;)[e,n]=[n,e%n];return e}class V{constructor(e,n=1n){if(0n===n)throw new D("division by zero");n<0n&&(e=-e,n=-n);const t=U(e,n)||1n;if(this.n=e/t,this.d=n/t,P(this.n)>W||P(this.d)>W)throw new D("a number too large to keep exactly")}static of(e){return new V(BigInt(e))}add(e){return new V(this.n*e.d+e.n*this.d,this.d*e.d)}sub(e){return new V(this.n*e.d-e.n*this.d,this.d*e.d)}mul(e){return new V(this.n*e.n,this.d*e.d)}div(e){if(0n===e.n)throw new D("division by zero");return new V(this.n*e.d,this.d*e.n)}neg(){return new V(-this.n,this.d)}abs(){return this.n<0n?this.neg():this}inv(){return V.ONE.div(this)}pow(e){if((e=BigInt(e))<0n)return this.inv().pow(-e);if((0n===this.n||1n===R(this.n))&&1n===this.d)return 0n===e||-1n===this.n&&e%2n==0n?V.ONE:this;if(BigInt(Math.max(P(this.n),P(this.d)))*e>BigInt(W))throw new D("a power too large to work out exactly");return new V(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 V(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(P(this.n),P(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 L(e){const n=/^(-?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(String(e));if(!n||""===n[2]&&!n[3])return null;const[,t,s,i="",r="0"]=n;let o=new V(BigInt((s||"0")+i),10n**BigInt(i.length));const a=Number(r);return a&&(o=o.mul(V.of(10).pow(a))),t?o.neg():o}function _(e,n){if(e<2n)return e;if(n>=P(e))return 1n;const t=BigInt(n);let s=1n<<BigInt(Math.ceil(P(e)/n));for(;;){const n=((t-1n)*s+e/s**(t-1n))/t;if(n>=s)break;s=n}for(;s**t>e;)s--;for(;(s+1n)**t<=e;)s++;return s}V.ZERO=new V(0n),V.ONE=new V(1n),V.MINUS_ONE=new V(-1n),V.HALF=new V(1n,2n);const H=(()=>{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 Q(e,n){const t=BigInt(n);let s=1n,i=1n,r=e;for(const e of H){if(e*e>r)break;if(r%e)continue;let n=0n;for(;r%e===0n;)r/=e,n++;s*=e**(n/t),i*=e**(n%t)}if(r>1n){const e=function(e,n){if(e<0n)return null;if(e<2n)return e;const t=_(e,n);return t**BigInt(n)===e?t:null}(r,n);null!==e?s*=e:i*=r}return{outside:s,inside:i}}const J=new Set(["pi","e","π"]),K={complex:!1};function Y(e,n){const t=K.complex;K.complex=Boolean(e);try{return n()}finally{K.complex=t}}const G=e=>J.has(e)||K.complex&&"i"===e,X=e=>K.complex&&"atom"===e.k&&"sym"===e.node.type&&"i"===e.node.token,ee=e=>({k:"num",q:e}),ne=ee(V.ONE),te=ee(V.ZERO),se=ee(V.HALF),ie=e=>"num"===e.k,re=e=>({k:"atom",node:e}),oe=new WeakMap;function ae(e){let n=oe.get(e);return void 0===n&&oe.set(e,n=De(e).s),n}function ue(e){if("num"===e.k)return 0;if("atom"===e.k)return"sym"===e.node.type&&G(e.node.token)?0:1;if("add"===e.k)return Math.max(...e.terms.map(e=>ue(e.x)));let n=0;for(const t of e.fs){const e=ue(t.b);e&&(n+=e*(ie(t.e)?t.e.q.toNumber():1))}return n}function le(e,n){return"num"===e.k?n&&!ie(n)?3:0:X(e)?1.5:"atom"===e.k&&"sym"===e.node.type?G(e.node.token)?n&&!ie(n)?3:1:2:"atom"===e.k?3:4}const ce=(e,n)=>e<n?-1:e>n?1:0;function fe(e){const n=new Map,t=(e,t)=>{"atom"!==e.k||"sym"!==e.node.type||G(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,ie(n.e)?n.e.q.toNumber():1);else t(e,1);return n}function pe(e,n){const t=ue(n.x)-ue(e.x);if(t)return t;const s=fe(e.x),i=fe(n.x);for(const e of[...new Set([...s.keys(),...i.keys()])].sort()){const n=(i.get(e)??0)-(s.get(e)??0);if(n)return n}return ce(ae(e.x),ae(n.x))}function he(e,n){return e.isOne?n:e.isZero?te:ve([ee(e),n])}function de(e){if("num"===e.k)return{coef:e.q,rest:null};if("mul"!==e.k||e.c.isOne)return{coef:V.ONE,rest:e};const n=1===e.fs.length&&ie(e.fs[0].e)&&e.fs[0].e.q.isOne?e.fs[0].b:{k:"mul",c:V.ONE,fs:e.fs};return{coef:e.c,rest:n}}function me(e){let n=V.ZERO;const t=new Map,s=(e,n)=>{const s=ae(n),i=t.get(s);i?i.coef=i.coef.add(e):t.set(s,{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)s(e.coef,e.x)}else{const{coef:e,rest:n}=de(t);s(e,n)}const i=[...t.values()].filter(e=>!e.coef.isZero);return i.length?n.isZero&&1===i.length?he(i[0].coef,i[0].x):(i.sort(pe),{k:"add",c:n,terms:i}):ee(n)}function ge(e,n){if(!ie(n))return e.isOne?{coef:V.ONE,fs:[]}:{coef:V.ONE,fs:[{b:ee(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:V.ZERO,fs:[]}}if(e.isOne)return{coef:V.ONE,fs:[]};if(e.sign<0){if(t.d%2n==1n){const{coef:s,fs:i}=ge(e.neg(),n);return{coef:t.n%2n==0n?s:s.neg(),fs:i}}if(K.complex&&2n===t.d){const{coef:s,fs:i}=ge(e.neg(),n);return{coef:s,fs:[...i,{b:ye,e:ee(new V(t.n))}]}}return{coef:V.ONE,fs:[{b:ee(e),e:n}]}}if(!e.isInteger){const s=ge(new V(e.n),n),i=ge(new V(e.d),ee(t.neg()));return{coef:s.coef.mul(i.coef),fs:[...s.fs,...i.fs]}}const s=t.floor(),i=t.sub(s);if(BigInt(P(e.n))*i.n>BigInt(W)||i.d>1000n)return{coef:V.ONE,fs:[{b:ee(e),e:n}]};let r=s.isZero?V.ONE:e.pow(s.n);const{outside:o,inside:a}=Q(e.n**i.n,Number(i.d));r=r.mul(new V(o));return{coef:r,fs:a>1n?[{b:ee(new V(a)),e:ee(new V(1n,i.d))}]:[]}}function ve(e){let n=V.ONE;const t=new Map,s=(e,n)=>{const s=ae(e),i=t.get(s);i?i.e=me([i.e,n]):t.set(s,{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)s(e.b,e.e)}else s(t,ne);if(n.isZero)return te;const i=[],r=new Map;for(const e of t.values())if(!ie(e.e)||!e.e.q.isZero){if("num"===e.b.k){if(ie(e.e)&&!e.e.q.isInteger&&e.b.q.sign>0&&e.b.q.isInteger){const n=e.e.q.toString(),t=r.get(n);t?t.n*=e.b.q.n:r.set(n,{n:e.b.q.n,e:e.e});continue}const t=ge(e.b.q,e.e);n=n.mul(t.coef),i.push(...t.fs);continue}if("mul"===e.b.k&&ie(e.e)&&e.e.q.isInteger){const t=be(e.b,e.e);"mul"===t.k?(n=n.mul(t.c),i.push(...t.fs)):"num"===t.k?n=n.mul(t.q):i.push({b:t,e:ne});continue}i.push(e)}for(const{n:e,e:t}of r.values()){const s=ge(new V(e),t);n=n.mul(s.coef),i.push(...s.fs)}if(n.isZero)return te;const o=new Map;for(const e of i){const n=ae(e.b),t=o.get(n);t?t.e=me([t.e,e.e]):o.set(n,{...e})}let a=[...o.values()].filter(e=>!(ie(e.e)&&e.e.q.isZero));if(K.complex){a=a.flatMap(e=>{if(!X(e.b)||!ie(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:ne}]:[]});const e=a.filter(e=>"add"===e.b.k&&ie(e.e)&&e.e.q.isInteger&&qe(e.b)),t=a.some(e=>X(e.b)),s=e.every(e=>(e.e.q.sign<0?-e.e.q.n:e.e.q.n)<=60n);if(e.length&&s&&(e.length>1||t||!e[0].e.q.isOne)){const s=a.filter(n=>!e.includes(n)&&!X(n.b));let i=t?[ye]:[ne];for(const n of e){const e=n.e.q.sign<0?Se(n.b):n.b;for(let t=0n;t<(n.e.q.sign<0?-n.e.q.n:n.e.q.n);t++)i=ke(i,Ue(e))}return ve([ee(n),me(i),...s.map(e=>we(e.b,e.e))])}}if(a.some(e=>"num"===e.b.k&&ie(e.e)&&e.e.q.compare(V.ONE)>=0))return ve([ee(n),...a.map(e=>"num"===e.b.k?be(e.b,e.e):{k:"mul",c:V.ONE,fs:[e]})]);if(!a.length)return ee(n);if(1===a.length&&!n.isOne&&"add"===a[0].b.k&&ie(a[0].e)&&a[0].e.q.isOne){const e=a[0].b;return me([ee(n.mul(e.c)),...e.terms.map(e=>he(n.mul(e.coef),e.x))])}return n.isOne&&1===a.length&&ie(a[0].e)&&a[0].e.q.isOne?a[0].b:(a=a.sort((e,n)=>le(e.b,e.e)-le(n.b,n.e)||ce(ae(e.b),ae(n.b))),{k:"mul",c:n,fs:a})}function be(e,n){if(K.complex&&ie(n)&&n.q.isInteger){if(X(e))return ve([{k:"mul",c:V.ONE,fs:[{b:e,e:n}]}]);if("add"===e.k&&qe(e)&&!n.q.isOne)return ve([{k:"mul",c:V.ONE,fs:[{b:e,e:n}]}])}if(ie(n)){if(n.q.isZero){if(ie(e)&&e.q.isZero)throw new D("0^0 is undefined");return ne}if(n.q.isOne)return e}if(ie(e)){const t=ge(e.q,n);if(!t.fs.length)return ee(t.coef);if(t.fs.some(e=>X(e.b)))return ve([ee(t.coef),...t.fs.map(e=>({k:"mul",c:V.ONE,fs:[e]}))]);const s={k:"mul",c:t.coef,fs:t.fs};return t.coef.isOne&&1===t.fs.length&&ie(t.fs[0].e)&&t.fs[0].e.q.isOne?t.fs[0].b:s}if(K.complex&&ie(n)&&2n===n.q.d&&qe(e)){const t=$e(e);if(t&&ie(t.im)&&!t.im.q.isZero){const e=e=>be(e,ee(V.of(2))),s=be(me([e(t.re),e(t.im)]),se),i=be(ve([me([s,t.re]),ee(V.HALF)]),se),r=be(ve([me([s,Oe(t.re)]),ee(V.HALF)]),se);return be(me([i,ve([ee(V.of(t.im.q.sign)),r,ye])]),ee(new V(n.q.n)))}}if("mul"===e.k){if(ie(n)&&n.q.isInteger)return ve([ee(e.c.pow(n.q.n)),...e.fs.map(e=>we(e.b,ve([e.e,n])))]);if(!e.c.isOne&&e.c.sign>0)return ve([be(ee(e.c),n),be({k:"mul",c:V.ONE,fs:e.fs},n)]);if(e.c.isOne&&1===e.fs.length){const[t]=e.fs;if(ie(t.e)&&ie(n)&&1n===t.e.q.n&&t.e.q.d%2n==1n)return we(t.b,ve([t.e,n]))}}return{k:"mul",c:V.ONE,fs:[{b:e,e:n}]}}function we(e,n){return ie(n)&&n.q.isZero?ne:ie(e)?be(e,n):ie(n)&&n.q.isOne?e:{k:"mul",c:V.ONE,fs:[{b:e,e:n}]}}const ye=re(k("i")),xe=e=>K.complex&&De(e).s.split(" ").includes("i");function qe(e){return K.complex&&xe(e)&&0===Pe(De(e)).size}function ke(e,n){const t=[];for(const s of e)for(const e of n)t.push(ve([s,e]));return Ue(me(t))}function $e(e){const n=[],t=[];for(const s of Ue(e)){const{coef:e,rest:i}=de(s),r=i?Ve(i):[],o=r.filter(e=>X(e)),a=r.filter(e=>!X(e));if(a.some(e=>xe(e)))return null;(o.length?t:n).push(ve([ee(e),...a]))}return{re:me(n),im:me(t)}}function Se(e){const n=$e(e);if(!n)return be(e,ee(V.MINUS_ONE));const t=me([be(n.re,ee(V.of(2))),be(n.im,ee(V.of(2)))]);return ve([me([n.re,ve([ee(V.MINUS_ONE),n.im,ye])]),be(t,ee(V.MINUS_ONE))])}const Me={re:([e])=>$e(e)?.re??null,im:([e])=>$e(e)?.im??null,conj:([e])=>{const n=$e(e);return n?me([n.re,ve([ee(V.MINUS_ONE),n.im,ye])]):null},arg:([e])=>{const n=$e(e);return n?Te("atan2",[n.im,n.re]):null},abs:([e])=>{const n=$e(e);return!n||ie(n.im)&&n.im.q.isZero?null:be(me([be(n.re,ee(V.of(2))),be(n.im,ee(V.of(2)))]),se)}},Ne={Re:"re",re:"re",Im:"im",im:"im",conj:"conj",overline:"conj",bar:"conj",arg:"arg"},Oe=e=>ve([ee(V.MINUS_ONE),e]),Ie=(e,n)=>ve([e,be(n,ee(V.MINUS_ONE))]),Ae=3000n,Ee={abs:([e])=>ie(e)?ee(e.q.abs()):"mul"!==e.k||e.c.isOne?null:ve([ee(e.c.abs()),Te("abs",[de(e).rest])]),floor:([e])=>ie(e)?ee(e.q.floor()):null,ceil:([e])=>ie(e)?ee(e.q.ceil()):null,"!":([e])=>{if(!ie(e)||!e.q.isInteger||e.q.sign<0||e.q.n>Ae)return null;let n=1n;for(let t=2n;t<=e.q.n;t++)n*=t;return ee(new V(n))},mod:([e,n])=>ie(e)&&ie(n)&&!n.q.isZero?ee(e.q.sub(n.q.mul(e.q.div(n.q).floor()))):null,max:e=>e.every(ie)&&e.length?e.reduce((e,n)=>n.q.compare(e.q)>0?n:e):null,min:e=>e.every(ie)&&e.length?e.reduce((e,n)=>n.q.compare(e.q)<0?n:e):null,gcd:e=>e.length&&e.every(e=>ie(e)&&e.q.isInteger)?ee(new V(e.reduce((e,n)=>U(e,n.q.n),0n))):null,log:([e,n])=>{if(!ie(e)||!ie(n)||e.q.sign<=0||n.q.sign<=0||e.q.isOne)return null;if(n.q.isOne)return te;const t=Math.log(n.q.toNumber())/Math.log(e.q.toNumber());if(!Number.isFinite(t))return null;for(let s=1;s<=12;s++){const i=Math.round(t*s);if(!(Math.abs(t*s-i)>1e-9||0===i)&&(Math.abs(i)<=256&&e.q.pow(BigInt(i)).equals(n.q.pow(BigInt(s)))))return ee(new V(BigInt(i),BigInt(s)))}return null},comb:([e,n])=>ie(e)&&ie(n)&&e.q.isInteger&&n.q.isInteger&&e.q.sign>=0&&n.q.sign>=0&&e.q.n<=Ae?ee(function(e,n){if(n>e)return V.ZERO;n>e-n&&(n=e-n);let t=1n;for(let s=1n;s<=n;s++)t=t*(e-n+s)/s;return new V(t)}(e.q.n,n.q.n)):null,perm:([e,n])=>{if(!(ie(e)&&ie(n)&&e.q.isInteger&&n.q.isInteger&&e.q.sign>=0&&n.q.sign>=0&&e.q.n<=Ae))return null;if(n.q.n>e.q.n)return te;let t=1n;for(let s=0n;s<n.q.n;s++)t*=e.q.n-s;return ee(new V(t))}};function Te(e,n){if(K.complex&&Me[e]){const t=Me[e](n);if(t)return t}const t=Ee[e];if(t){const e=t(n);if(e)return e}return re(N(e,n.map(De)))}const je=new Map;function ze(e){const n=K.complex?`ℂ ${e.s}`:e.s,t=je.get(n);if(t)return t;const s=function(e){if("num"===e.type){const n=L(e.token);if(!n)throw new D(`not an exact number: ${e.token}`);return ee(n)}if("sym"===e.type)return"π"===e.token?re(k("pi")):re(e);const n=e.args.map(ze);switch(e.op){case"+":return me(n);case"-":return((e,n)=>me([e,Oe(n)]))(n[0],n[1]);case"neg":return Oe(n[0]);case"*":return ve(n);case"/":return Ie(n[0],n[1]);case"^":return be(n[0],n[1]);case"sqrt":return be(n[0],se);case"root":return be(n[1],be(n[0],ee(V.MINUS_ONE)));default:{const t=e.op.startsWith("\\:")?e.op.slice(2):null;return t&&K.complex&&Ne[t]&&1===n.length?Te(Ne[t],n):t&&d(t)&&h(t).arity===n.length?Te(t,n):Te(e.op,n)}}}(e);return je.size>2e4&&je.clear(),je.set(n,s),s}const Ze=e=>De(ze(e)),Ce=e=>$(String(e));function Fe(e){return e.isInteger?Ce(e.n):N("/",[Ce(e.n),Ce(e.d)])}const Be=new WeakMap;function De(e){let n=Be.get(e);return n||Be.set(e,n=function(e){switch(e.k){case"num":return Fe(e.q);case"atom":return e.node;case"mul":return function(e,n){const t=[],s=[];for(const e of n)ie(e.e)&&e.e.q.sign<0?s.push(We(e.b,ee(e.e.q.neg()))):t.push(We(e.b,e.e));let i=1n!==e.n&&-1n!==e.n||!t.length?Re([Ce(e.n),...t]):Re(t);-1n===e.n&&t.length&&(i=N("neg",[i]));1n!==e.d&&s.unshift(Ce(e.d));return s.length?N("/",[i,Re(s)]):i}(e.c,e.fs);case"add":return function(e){let n=null;const t=e=>K.complex&&xe(e.x)&&0===Pe(De(e.x)).size,s=[...e.terms.filter(e=>!t(e)),...e.terms.filter(t)],i=e.c,r=()=>{i.isZero||(n=n?i.sign<0?N("-",[n,Fe(i.neg())]):N("+",[n,Fe(i)]):Fe(i))};let o=!1;for(const e of s)!o&&t(e)&&(r(),o=!0),n=n?e.coef.sign<0?N("-",[n,De(he(e.coef.neg(),e.x))]):N("+",[n,De(he(e.coef,e.x))]):De(he(e.coef,e.x));o||r();return n}(e);default:throw new Error(`bad form ${e.k}`)}}(e)),n}function We(e,n){const t=De(e);if(ie(n)){const e=n.q;if(e.isOne)return t;if(1n===e.n&&2n===e.d)return N("sqrt",[t]);if(1n===e.n)return N("root",[Ce(e.d),t])}return N("^",[t,De(n)])}const Re=e=>e.reduce((e,n)=>e?N("*",[e,n]):n,null);function Pe(e,n=new Set){if("sym"===e.type)G(e.token)||n.add(e.token);else if(I(e))for(const t of e.args)Pe(t,n);return n}function Ue(e){if("add"!==e.k)return[e];const n=e.terms.map(e=>he(e.coef,e.x));return e.c.isZero||n.push(ee(e.c)),n}function Ve(e){if("num"===e.k)return[e];if("mul"!==e.k)return[e];const n=e.c.isOne?[]:[ee(e.c)];for(const t of e.fs)n.push(we(t.b,t.e));return n}const Le="_",_e=new WeakMap;function He(e,n){return[...n,...h(e.op)?.arity===u?[String(e.args.length)]:[],e.op].join(" ")}function Qe(e,n){let t=_e.get(e);t||_e.set(e,t=new Map);const s=t.get(n);if(s)return s;const i=function(e,n){const t={key:Le,slots:[e]};if(e.type!==w||n<=0)return[t];const s=e.args.map(e=>Qe(e,n-1)),i=[t],r=new Array(s.length).fill(0);for(;;){const n=[],t=[];for(let e=0;e<s.length;e++){const i=s[e][r[e]];n.push(i.key);for(const e of i.slots)t.push(e)}if(i.push({key:He(e,n),slots:t}),i.length>=4096)break;let o=s.length-1;for(;o>=0&&!(++r[o]<s[o].length);o--)r[o]=0;if(o<0)break}return i}(e,n);return t.set(n,i),i}function Je(e){return e.type!==w?Le:He(e,e.args.map(Je))}function Ke(e,n=[]){if(e.type!==w)n.push(e);else for(const t of e.args)Ke(t,n);return n}const Ye=new Map,Ge=new Map;class Xe extends Error{constructor(e){super(e),this.name="RequirementError"}}function en(e,n,t=""){Ye.set(e,{name:e,fn:n,doc:t,arity:Math.max(0,n.length-1)})}function nn(e,n,t=""){Ge.set(e,{name:e,fn:n,doc:t})}function tn(e){return Ye.get(e)||null}function sn(e){return Ge.get(e)||null}const rn=e=>e.type===v;function on(e,n){return e.type===w&&(e.op===n||e.args.some(e=>on(e,n)))}en("always",()=>!0,"matches anything"),en("never",()=>!1,"matches nothing"),en("isLeaf",e=>e.type!==w,"a bare operand, not an operation"),en("isCompound",e=>e.type===w,"an operation, not a bare operand"),en("isSymbol",e=>e.type===b,"a non-numeric operand such as x"),en("isOperation",(e,n)=>e.type===w&&e.op===n,"is this specific operation"),en("notOperation",(e,n)=>!(e.type===w&&e.op===n),"is anything except this operation"),en("isNumber",rn,"a numeric literal"),en("isInteger",e=>rn(e)&&Number.isInteger(e.value),"a whole number"),en("isPositive",e=>rn(e)&&e.value>0,"greater than zero"),en("isNegative",e=>rn(e)&&e.value<0,"less than zero"),en("isNonNegative",e=>rn(e)&&e.value>=0,"zero or greater"),en("isZero",e=>rn(e)&&0===e.value,"exactly 0"),en("isOne",e=>rn(e)&&1===e.value,"exactly 1"),en("isNonZero",e=>rn(e)&&0!==e.value,"a number that is provably not 0"),en("isNotZeroLiteral",e=>!(rn(e)&&0===e.value),"anything except a literal 0"),en("isPositiveInteger",e=>rn(e)&&Number.isInteger(e.value)&&e.value>0,"a whole number above 0"),en("isNegativeInteger",e=>rn(e)&&Number.isInteger(e.value)&&e.value<0,"a whole number below 0"),en("isEven",e=>rn(e)&&Number.isInteger(e.value)&&e.value%2==0,"a whole even number"),en("isOdd",e=>rn(e)&&Number.isInteger(e.value)&&1===Math.abs(e.value%2),"a whole odd number"),en("greaterThan",(e,n)=>rn(e)&&e.value>Number(n),"above a given value"),en("lessThan",(e,n)=>rn(e)&&e.value<Number(n),"below a given value"),en("isValue",(e,n)=>rn(e)&&e.value===Number(n),"equals a given number"),en("isNumeric",Z,"contains no symbols: a constant (it need not fold to a number: 1 sin)"),en("hasSymbol",e=>!Z(e),"mentions a symbol somewhere, so it is not just a number"),en("isVar",(e,n)=>e.type===b&&e.token===String(n),"is exactly this symbol"),en("contains",(e,n)=>z(e).includes(String(n)),"mentions this operand somewhere"),en("isFree",(e,n)=>!z(e).includes(String(n)),"never mentions this operand"),en("hasOperation",(e,n)=>on(e,String(n)),"uses this operation somewhere inside"),en("equals",(e,n)=>e.s===String(n),"is exactly this postfix expression");const an=e=>e.type===w?null:e.token;function un(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 Xe(`bad requirement: ${JSON.stringify(e)}`)}nn("freeOf",(e,n)=>{const t=an(n);return null!==t&&!z(e).includes(t)},"the first operand never mentions the second"),nn("dependsOn",(e,n)=>{const t=an(n);return null!==t&&z(e).includes(t)},"the first operand does mention the second"),nn("sameAs",(...e)=>e.every(n=>n.s===e[0].s),"these operands are structurally identical"),nn("differs",(...e)=>new Set(e.map(e=>e.s)).size===e.length,"these operands are all different"),nn("sameValue",(...e)=>e.every(e=>rn(e))&&e.every(n=>n.value===e[0].value),"these operands are the same number");const ln="simplify";class cn extends Error{constructor(e,n){super(n?`rule "${n}": ${e}`:e),this.name="RuleError",this.ruleId=n}}const fn=/^[A-Za-z_][A-Za-z0-9_]*$/;function pn(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 cn('"=" needs an operand after it',n);return{token:e}}if(!fn.test(t))throw new cn(`"${t}" is not a usable slot name; use letters, digits and _`,n);if(d(t))throw new cn(`slot name "${t}" collides with an operator`,n);return{name:t}}function hn(e){if(!I(e))return[e];const n=e.args.map(hn),t=h(e.op),s=[];for(const i of function(e){let n=[[]];for(const t of e){const e=[];for(const s of n)for(const n of t)e.push(s.concat([n]));if(n=e,n.length>64)return n.slice(0,64)}return n}(n))if(s.push(N(e.op,i)),t.commutative&&2===i.length&&i[0].s!==i[1].s&&s.push(N(e.op,[i[1],i[0]])),s.length>=64)break;return s}function dn(e,n=[]){return"op"===e.kind?e.args.forEach(e=>dn(e,n)):"const"===e.kind&&e.free&&n.push(e.node.token),n}function mn(e){if(!e||"object"!=typeof e)throw new cn("rule must be a mapping");const n=e.id||e.name;if(!n)throw new cn("rule needs an id");if(!e.pattern)throw new cn("rule needs a pattern",n);if(void 0===e.output||null===e.output)throw new cn("rule needs an output",n);let t;try{t=A(String(e.pattern))}catch(e){if(e instanceof x)throw new cn(`bad pattern: ${e.message}`,n);throw e}const s=Ke(t).map(e=>pn(e,n)),i=new Set(s.filter(e=>e.name).map(e=>e.name)),r=function(e,n,t){const s=[],i=e.when||{};if("object"!=typeof i||Array.isArray(i))throw new cn('"when" must map slot names to lists of requirements',t);for(const[e,r]of Object.entries(i)){if(!n.has(e))throw new cn(`"when" mentions "${e}", which is not a slot in the pattern`,t);const i=Array.isArray(r)?r:[r];for(const n of i){const{name:i,args:r}=un(n),o=tn(i);if(!o)throw new cn(`unknown requirement "${i}"`,t);s.push({slot:e,name:i,args:r,fn:o.fn})}}return s}(e,i,n),o=function(e,n,t){const s=[],i=e.require||[];if(!Array.isArray(i))throw new cn('"require" must be a list of relations',t);for(const e of i){const{name:i,args:r}=un(e),o=sn(i);if(!o)throw new cn(`unknown relation "${i}"`,t);if(r.length<2)throw new cn(`relation "${i}" needs at least two operands`,t);for(const e of r)if("string"==typeof e&&!n.has(e)&&fn.test(e))throw new cn(`relation "${i}" mentions "${e}", which is not a slot in the pattern`,t);s.push({name:i,args:r,fn:o.fn})}return s}(e,i,n),a=function(e,n,t){let s;try{s=A(e)}catch(n){throw new cn(`bad output "${e}": ${n.message}`,t)}const i=e=>I(e)?{kind:"op",op:e.op,args:e.args.map(i)}:O(e)?{kind:"const",node:e}:n.has(e.token)?{kind:"slot",name:e.token}:e.token.startsWith("=")?{kind:"const",node:k(e.token.slice(1))}:{kind:"const",node:e,free:!0};return i(s)}(String(e.output),i,n),u=e.commutative?hn(t):[t],l=[],c=new Set;for(const e of u){const t=Je(e),s=Ke(e).map(e=>pn(e,n)),i=t+"\0"+s.map(e=>e.name??(void 0!==e.literal?`#${e.literal}`:`=${e.token}`)).join(",");c.has(i)||(c.add(i),l.push({key:t,slots:s}))}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):ln,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:r,require:o,slots:[...i],depth:T(t),bindings:l,freeSymbols:dn(a),source:e};for(const e of l)e.rule=f;return f}function gn(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!==ln&&(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 vn extends Error{constructor(e,n){super(null==n?e:`${e} (line ${n+1})`),this.name="YamlError",this.line=n}}class bn{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 wn=e=>"-"===e||e.startsWith("- ");function yn(e){let n=null,t=0;for(let s=0;s<e.length;s++){const i=e[s];if(n)i===n?"'"===n&&"'"===e[s+1]?s++:n=null:'"'===n&&"\\"===i&&s++;else if('"'===i||"'"===i)n=i;else if("["===i||"{"===i)t++;else if("]"===i||"}"===i)t--;else if(":"===i&&0===t&&(s+1===e.length||" "===e[s+1])){const n=e.slice(0,s).trim();return""===n?null:{key:xn(n),rest:e.slice(s+1).trim()}}}return null}function xn(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 qn(e){const n=new bn(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 s=function(e){let n=null;for(let t=0;t<e.length;t++){const s=e[t];if(n)s===n?"'"===n&&"'"===e[t+1]?t++:n=null:'"'===n&&"\\"===s&&t++;else if('"'===s||"'"===s)n=s;else if("#"===s&&(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:s,blank:""===s}})}(e));let t=n.peek();if(t&&"---"===t.text&&(n.next(),t=n.peek()),!t)return null;const s=$n(n,t.indent),i=n.peek();if(i&&"..."!==i.text&&"---"!==i.text)throw new vn(`unexpected content "${i.text}"`,i.n);return s}const kn=/^[|>][-+]?\d*$/;function $n(e,n){const t=e.peek();return!t||t.indent<n?null:wn(t.text)?Sn(e,t.indent):yn(t.text)?function(e,n){const t={};for(;;){const s=e.peek();if(!s||s.indent!==n)break;const i=yn(s.text);if(!i)break;e.next();const{key:r,rest:o}=i;if(""===o){const s=e.peek();s&&s.indent>n?t[r]=$n(e,s.indent):s&&s.indent===n&&wn(s.text)?t[r]=Sn(e,n):t[r]=null}else kn.test(o)?t[r]=Mn(e,o,n):t[r]=Nn(o,s.n)}return t}(e,t.indent):(e.next(),kn.test(t.text)?Mn(e,t.text,t.indent-1):Nn(t.text,t.n))}function Sn(e,n){const t=[];for(;;){const s=e.peek();if(!s||s.indent!==n||!wn(s.text))break;if(e.next(),"-"===s.text){const s=e.peek();t.push(s&&s.indent>n?$n(e,s.indent):null);continue}if(kn.test(s.text.slice(2).trim())){t.push(Mn(e,s.text.slice(2).trim(),n));continue}const i=s.text.slice(2),r=n+2+(i.length-i.trimStart().length);e.push({raw:s.raw,n:s.n,indent:r,text:i.trim(),blank:!1}),t.push($n(e,r))}return t}function Mn(e,n,t){const s=n[0],i=(n.match(/[-+]/)||[""])[0],r=(n.match(/\d+/)||[null])[0];let o=r?t+Number(r):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 s=n.raw.search(/\S/);if(s<=t)break;if(null===o&&(o=s),s<o)break;a.push(n.raw.slice(o)),e.i++}for(;a.length&&""===a[a.length-1];)a.pop();let u;if("|"===s)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"-"===i?u:"+"===i?u+"\n":""===u?"":u+"\n"}function Nn(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},s=In(t);if(On(t),t.i<t.text.length)throw new vn(`unexpected "${t.text.slice(t.i)}" in flow value`,n);return s}(t,n):'"'===t[0]||"'"===t[0]?xn(t):/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(t)?Number(t):t)}const On=e=>{for(;e.i<e.text.length&&/\s/.test(e.text[e.i]);)e.i++};function In(e){On(e);const n=e.text[e.i];return"["===n?function(e){e.i++;const n=[];for(;;){if(On(e),e.i>=e.text.length)throw new vn("unterminated [",e.line);if("]"===e.text[e.i])return e.i++,n;if(n.push(In(e)),On(e),","===e.text[e.i])e.i++;else if("]"!==e.text[e.i])throw new vn(`expected , or ] near "${e.text.slice(e.i)}"`,e.line)}}(e):"{"===n?function(e){e.i++;const n={};for(;;){if(On(e),e.i>=e.text.length)throw new vn("unterminated {",e.line);if("}"===e.text[e.i])return e.i++,n;const t=String(In(e));if(On(e),":"!==e.text[e.i])throw new vn(`expected : after "${t}"`,e.line);if(e.i++,n[t]=In(e),On(e),","===e.text[e.i])e.i++;else if("}"!==e.text[e.i])throw new vn(`expected , or } near "${e.text.slice(e.i)}"`,e.line)}}(e):Nn(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 vn("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 An=/^(true|false|null|yes|no|on|off|~)$/i;function En(e){if(null==e)return"null";if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e))throw new vn(`cannot serialize ${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)||An.test(e)||/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(e))}(n)?JSON.stringify(n):n}const Tn=e=>null==e||"object"!=typeof e;function jn(e){return Array.isArray(e)?`[${e.map(jn).join(", ")}]`:e&&"object"==typeof e?`{${Object.entries(e).map(([e,n])=>`${En(e)}: ${jn(n)}`).join(", ")}}`:En(e)}function zn(e){return Array.isArray(e)?!!e.every(e=>Tn(e)||Array.isArray(e)&&e.every(Tn))&&jn(e).length<=72:!(!e||"object"!=typeof e)&&(Object.values(e).every(e=>Tn(e)||Array.isArray(e)&&e.every(Tn))&&jn(e).length<=72)}function Zn(e){const n=[];return Cn(e,0,n),n.length?n.join("\n")+"\n":""}function Cn(e,n,t){const s=" ".repeat(n);if(Array.isArray(e)){if(0===e.length)return void t.push(s+"[]");for(const s of e)Fn(s,n,t)}else{if(e&&"object"==typeof e){const i=Object.entries(e).filter(([,e])=>void 0!==e);if(0===i.length)return void t.push(s+"{}");for(const[e,s]of i)Bn(e,s,n,t);return}!function(e,n,t){if("string"==typeof e&&e.includes("\n")){t.push(n+"|-");for(const s of e.replace(/\n+$/,"").split("\n"))t.push(n+" "+s);return}t.push(n+En(e))}(e,s,t)}}function Fn(e,n,t){const s=" ".repeat(n);if(null!==e&&"object"==typeof e&&!zn(e)){const i=[];if(Cn(e,n+2,i),0===i.length)return void t.push(s+"-");t.push(s+"- "+i[0].slice(n+2));for(let e=1;e<i.length;e++)t.push(i[e]);return}if(null===e||"object"!=typeof e)if("string"==typeof e&&e.includes("\n")){t.push(s+"- |-");for(const s of e.replace(/\n+$/,"").split("\n"))t.push(" ".repeat(n+4)+s)}else t.push(s+"- "+En(e));else t.push(s+"- "+jn(e))}function Bn(e,n,t,s){const i=" ".repeat(t),r=En(e);if("string"==typeof n&&n.includes("\n")){s.push(`${i}${r}: |-`);for(const e of n.replace(/\n+$/,"").split("\n"))s.push(" ".repeat(t+2)+e)}else{if(null!==n&&"object"==typeof n)return zn(n)?void s.push(`${i}${r}: ${jn(n)}`):(s.push(`${i}${r}:`),void Cn(n,Array.isArray(n)?t:t+2,s));s.push(`${i}${r}: ${En(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:mn(e);if(this.rules.some(e=>e.id===n.id))throw new cn(`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===ln?-1:n===ln?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=qn(e);return Dn.fromSpecs(t,{strict:n})}static fromSpecs(e,{strict:n=!0}={}){let t=e,s="";if(e&&!Array.isArray(e)&&"object"==typeof e&&(t=e.rules,s=e.name?String(e.name):""),!Array.isArray(t))throw new cn('expected a list of rules, or a mapping with a "rules" list');const i=new Dn;i.name=s;const r=[];for(let e=0;e<t.length;e++)try{i.add(t[e])}catch(n){r.push(`#${e+1}: ${n.message}`)}if(r.length&&n)throw new cn(`${r.length} rule(s) failed to compile:\n ${r.join("\n ")}`);return i.errors=r,i}toSpecs(){return this.rules.map(gn)}toYaml(){const e=this.toSpecs();return this.name?Zn({name:this.name,rules:e}):Zn(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 Wn(e,n){const t=Object.create(null),s=e.slots;for(let e=0;e<s.length;e++){const i=s[e],r=n[e];if(void 0!==i.literal){if(!O(r)||r.value!==i.literal)return null;continue}if(void 0!==i.token){if(r.s!==i.token)return null;continue}const o=t[i.name];if(void 0!==o){if(o.s!==r.s)return null}else t[i.name]=r}return t}function Rn(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 Pn(e,n){return n.rule.priority-e.rule.priority||n.rule.depth-e.rule.depth}function Un(e,n){const t=[];if(0===n.maxDepth)return t;for(const{key:s,slots:i}of function(e,n){const t=Qe(e,n),s=[];for(const e of t)e.key!==Le&&s.push(e);return s}(e,n.maxDepth)){const e=n.candidates(s);if(e)for(const n of e){const e=Wn(n,i);e&&(Rn(n.rule,e)&&t.push({rule:n.rule,binding:n,key:s,bound:e}))}}return t.sort(Pn)}function Vn(e,n,{order:t="post"}={}){const s=[];for(const{node:i,path:r}of C(e,t))for(const e of Un(i,n))s.push({...e,node:i,path:r});return s}function Ln(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 N(e.op,e.args.map(e=>Ln(e,n)));default:throw new Error(`bad output template: ${JSON.stringify(e)}`)}}function _n(e){if(!I(e))return e;const n=e.args.map(_n),t=n.some((n,t)=>n!==e.args[t])?N(e.op,n):e,s=h(t.op);if(!s||!s.fold||!t.args.every(O))return t;if(Qn.has(t.op)){const e=function(e,n){const[t,s]=n.map(Kn);if(!t||n.length>1&&!s)return;let i;switch(e){case"neg":i={n:-t.n,scale:t.scale};break;case"+":{const[e,n,r]=Yn(t,s);i={n:e+n,scale:r};break}case"-":{const[e,n,r]=Yn(t,s);i={n:e-n,scale:r};break}case"*":i={n:t.n*s.n,scale:t.scale+s.scale};break;case"^":{if(0!==s.scale||s.n>64n||s.n<-64n)return null;const e=s.n<0n?-s.n:s.n;if((t.n<0n?-t.n:t.n).toString().length*Number(e)>Jn)return null;const n={n:t.n**e,scale:t.scale*Number(e)};if(i=s.n<0n?function({n:e,scale:n}){if(0n===e)return null;let t=e<0n?-e:e,s=0,i=0;for(;t%2n==0n;)t/=2n,s++;for(;t%5n==0n;)t/=5n,i++;if(1n!==t)return null;const r=Math.max(s,i),o=10n**BigInt(n)*2n**BigInt(r-s)*5n**BigInt(r-i);return{n:e<0n?-o:o,scale:r}}(n):n,!i)return null;break}default:return}const r=function({n:e,scale:n}){const t=e<0n;let s=(t?-e:e).toString();n>0&&(s=s.padStart(n+1,"0"),s=`${s.slice(0,-n)}.${s.slice(-n)}`.replace(/\.?0+$/,""));return"0"===s?"0":(t?"-":"")+s}(i);return r.length>Jn?null:r}(t.op,t.args.map(e=>e.token));if(void 0!==e)return null===e?t:$(e)}const i=s.fold(...t.args.map(e=>e.value));return null!=i&&Number.isFinite(i)?q(i):t}function Hn(e,n){const t=function(e){const n=Ln(e.rule.outputTemplate,e.bound);return e.rule.fold?_n(n):n}(n);return{expr:B(e,n.path,t),before:n.node,after:t,rule:n.rule,path:n.path,explanation:(s=n.rule,i=n.bound,r=t,s.explain?s.explain.replace(/\{(\w+)\}/g,(e,n)=>{if("result"===n)return r?r.s:e;const t=i[n];return t?t.s:e}):"")};var s,i,r}const Qn=new Set(["+","-","*","neg","^"]),Jn=2e3;function Kn(e){const n=/^(-?)(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/i.exec(e);if(!n)return;const t=n[3]??"";let s=BigInt(n[2]+t),i=t.length-Number(n[4]??0);return i<0&&(s*=10n**BigInt(-i),i=0),{n:n[1]?-s:s,scale:i}}const Yn=(e,n)=>{const t=Math.max(e.scale,n.scale);return[e.n*10n**BigInt(t-e.scale),n.n*10n**BigInt(t-n.scale),t]};const Gn=4e5,Xn=()=>new D("a number too large to approximate"),et=e=>e<0n?-e:e;class nt{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 _(e*this.S,2)}series(e,n){let t=0n,s=e;for(let e=1;0n!==s;e++)if(t+=s,s=n(s,e),e>1e5)throw new D("a series did not converge");return t}atanhInv(e){const n=BigInt(e),t=n*n;let s=this.S/n,i=0n;for(let e=1n;0n!==s;e+=2n)i+=s/e,s/=t;return i}atanInv(e){const n=BigInt(e),t=n*n;let s=this.S/n,i=0n;for(let e=1n,n=1n;0n!==s;e+=2n,n=-n)i+=n*s/e,s/=t;return i}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(Gn))throw Xn();if(n<-BigInt(Gn))return 0n;const t=e-n*this.ln2,s=this.series(this.S,(e,n)=>e*t/this.S/BigInt(n));return n>=0n?s<<n:s>>-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 s=this.div(t-this.S,t+this.S),i=this.mul(s,s);let r=s,o=0n;for(let e=1n;0n!==r;e+=2n)o+=r/e,r=this.mul(r,i);return 2n*o+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 s=this.mul(t,t);return this.series(t,(e,n)=>-e*s/this.S/BigInt(2*n*(2*n+1)))}cos(e){return this.sin(e+this.pi/2n)}atan(e){if(et(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 s=n,i=0n;for(let e=1n,n=1n;0n!==s;e+=2n,n=-n)i+=n*s/e,s=this.mul(s,t);return 4n*i}asin(e){if(et(e)>this.S)throw new D("arcsin of a number beyond ±1 is not real");return et(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 tt(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 st={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 s=e.mul(t[0],t[0])+e.mul(t[1],t[1]);if(0n===s)throw new D("division by zero");return[e.div(e.mul(n[0],t[0])+e.mul(n[1],t[1]),s),e.div(e.mul(n[1],t[0])-e.mul(n[0],t[1]),s)]},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=st.abs(e,n);if(0n===t)throw new D("the log of 0 is undefined");return[e.ln(t),tt(e,n[1],n[0])]},pow(e,n,t,s){if(0n===n[0]&&0n===n[1])return[0n,0n];if(s&&s.isInteger){let t=s.n<0n?-s.n:s.n,i=[e.S,0n],r=n;for(;t>0n;)1n&t&&(i=st.mul(e,i,r)),r=st.mul(e,r,r),t>>=1n;return s.n<0n?st.div(e,[e.S,0n],i):i}return st.exp(e,st.mul(e,t,st.ln(e,n)))},sinh:(e,n)=>(e.exp(n)-e.exp(-n))/2n,cosh:(e,n)=>(e.exp(n)+e.exp(-n))/2n},it={sin:(e,[n,t])=>[e.mul(e.sin(n),st.cosh(e,t)),e.mul(e.cos(n),st.sinh(e,t))],cos:(e,[n,t])=>[e.mul(e.cos(n),st.cosh(e,t)),-e.mul(e.sin(n),st.sinh(e,t))],tan:(e,n)=>st.div(e,it.sin(e,n),it.cos(e,n)),ln:(e,n)=>st.ln(e,n),sqrt:(e,n)=>st.exp(e,st.mul(e,[e.S/2n,0n],st.ln(e,n))),sinh:(e,[n,t])=>[e.mul(st.sinh(e,n),e.cos(t)),e.mul(st.cosh(e,n),e.sin(t))],cosh:(e,[n,t])=>[e.mul(st.cosh(e,n),e.cos(t)),e.mul(st.sinh(e,n),e.sin(t))]},rt=e=>({q:e}),ot=([e,n])=>0n===n?{f:e}:{z:[e,n]};function at(e,n,t){const s=e=>((e,n)=>n.z??[ut(e,n),0n])(t,n[e]);switch(e.op){case"+":return ot(st.add(s(0),s(1)));case"-":return ot(st.sub(s(0),s(1)));case"neg":return ot([-s(0)[0],-s(0)[1]]);case"*":return ot(st.mul(t,s(0),s(1)));case"/":return ot(st.div(t,s(0),s(1)));case"^":return ot(st.pow(t,s(0),s(1),n[1].q));case"sqrt":return ot(it.sqrt(t,s(0)));case"root":return ot(st.pow(t,s(1),st.div(t,[t.S,0n],s(0)),n[0].q?.inv()));case"abs":return{f:st.abs(t,s(0))};case"arg":return{f:tt(t,s(0)[1],s(0)[0])};case"re":return{f:s(0)[0]};case"im":return{f:s(0)[1]};case"conj":return ot([s(0)[0],-s(0)[1]]);case"log":return ot(st.div(t,st.ln(t,s(1)),st.ln(t,s(0))));default:{const i=it[e.op];if(!i||1!==n.length)throw new D(`no complex value for ${e.op}`);return ot(i(t,s(0)))}}}function ut(e,n){return n.q?e.fromQ(n.q):n.f}const lt={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),arcsec:(e,n)=>{if(et(n)<e.S)throw new D("arcsec of a number between -1 and 1 is not real");return e.pi/2n-e.asin(e.div(e.S,n))},arccsc:(e,n)=>{if(et(n)<e.S)throw new D("arccsc of a number between -1 and 1 is not real");return e.asin(e.div(e.S,n))},arccot:(e,n)=>e.pi/2n-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),s=e.exp(-n);return e.div(t-s,t+s)},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(et(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 ct(e,n,t){if("num"===e.type)return rt(L(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&&K.complex)return{z:[0n,n.S]};if(t&&e.token in t){const n=t[e.token],s="number"==typeof n||"string"==typeof n||"bigint"==typeof n?L(String(n)):null;if(!s)throw new D(`the value of ${e.token} is not a number`);return rt(s)}throw new D(`${e.token} has no value`)}K.complex&&e.op.startsWith("\\:")&&Ne[e.op.slice(2)]&&(e=N(Ne[e.op.slice(2)],e.args));const s=e.args.map(e=>ct(e,n,t));if(s.some(e=>e.z)||["re","im","conj","arg"].includes(e.op)||function(e,n){if(!K.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,s))return at(e,s,n);const i=s.every(e=>e.q),r=e=>ut(n,s[e]);switch(e.op){case"+":return i?rt(s[0].q.add(s[1].q)):{f:r(0)+r(1)};case"-":return i?rt(s[0].q.sub(s[1].q)):{f:r(0)-r(1)};case"neg":return s[0].q?rt(s[0].q.neg()):{f:-s[0].f};case"*":return i?rt(s[0].q.mul(s[1].q)):{f:n.mul(r(0),r(1))};case"/":return i?rt(s[0].q.div(s[1].q)):{f:n.div(r(0),r(1))};case"^":return pt(n,s[0],s[1]);case"sqrt":return pt(n,s[0],rt(V.HALF));case"root":return pt(n,s[1],s[0].q?rt(s[0].q.inv()):{f:n.div(n.S,s[0].f)});case"abs":return s[0].q?rt(s[0].q.abs()):{f:et(s[0].f)};case"floor":return rt(s[0].q?s[0].q.floor():new V(ft(s[0].f,n.S)));case"ceil":return rt(s[0].q?s[0].q.ceil():new V(-ft(-s[0].f,n.S)));case"log":return{f:n.div(n.ln(r(1)),n.ln(r(0)))};case"atan2":return{f:tt(n,r(0),r(1))};case"max":case"min":if(!s.length)throw new D(`${e.op} of nothing`);return i?rt(s.map(e=>e.q).reduce((n,t)=>("max"===e.op?t.sub(n).sign>0:t.sub(n).sign<0)?t:n)):{f:s.map((e,n)=>r(n)).reduce((n,t)=>"max"===e.op?t>n?t:n:t<n?t:n)};case"sum":return i?rt(s.reduce((e,n)=>e.add(n.q),V.ZERO)):{f:s.reduce((e,n,t)=>e+r(t),0n)};case"prod":return i?rt(s.reduce((e,n)=>e.mul(n.q),V.ONE)):{f:s.reduce((e,t,s)=>n.mul(e,r(s)),n.S)};case"mean":if(!s.length)throw new D("mean of nothing");return i?rt(s.reduce((e,n)=>e.add(n.q),V.ZERO).div(new V(BigInt(s.length)))):{f:s.reduce((e,n,t)=>e+r(t),0n)/BigInt(s.length)};case"mod":{if(i){if(s[1].q.isZero)throw new D("mod 0 is undefined");return rt(s[0].q.sub(s[1].q.mul(s[0].q.div(s[1].q).floor())))}const e=r(1);if(0n===e)throw new D("mod 0 is undefined");return{f:r(0)-n.mul(e,ft(n.div(r(0),e),n.S)*n.S)}}case"round":{if(!s[1].q?.isInteger)throw new D("round needs a whole number of places");const e=10n**et(s[1].q.n),t=s[0].q??new V(r(0),n.S),i=s[1].q.sign>=0,o=(i?t.mul(new V(e)):t.div(new V(e))).add(V.HALF).floor();return rt(i?o.div(new V(e)):o.mul(new V(e)))}case"!":{if(!s[0].q?.isInteger||s[0].q.sign<0)throw new D("factorial is only worked out for whole numbers");let e=1n;for(let n=2n;n<=s[0].q.n;n++)if(e*=n,0n==(255n&n)&&P(e)>Gn)throw Xn();return rt(new V(e))}default:{const t=lt[e.op];if(!t||1!==s.length)throw new D(`no numeric value for ${e.op}`);return{f:t(n,r(0))}}}}const ft=(e,n)=>{const t=e/n;return e<0n&&t*n!==e?t-1n:t};function pt(e,n,t){if(t.q&&t.q.isInteger){if(n.q)return rt(n.q.pow(t.q.n));let s=t.q.n;const i=s<0n;i&&(s=-s);let r=e.S,o=n.f;for(;s>0n;){if(1n&s&&(r=e.mul(r,o)),o=e.mul(o,o),P(r)>Gn+4*e.P||P(o)>8e5){if(i)return{f:0n};throw Xn()}s>>=1n}return{f:i?e.div(e.S,r):r}}const s=ut(e,n);if(0n===s){if(t.q?t.q.sign>0:t.f>0n)return rt(V.ZERO);throw new D("0 to a power that is not positive is undefined")}if(s<0n){if(t.q&&t.q.d%2n==1n){const n=pt(e,{f:-s},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===et(t.q.n)&&t.q.d<=64n){const n=_(s*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(ut(e,t),e.ln(s)))}}function ht(e,n,t){const s=e<0n?"-":"",i=et(e);if(0n===i)return{sign:"",digits:"0",point:1};const r=i.toString(),o=r.length-n.P;let a=r.slice(0,t);r.length>t&&r[t]>="5"&&(a=(BigInt(a)+1n).toString());let u=o;return a.length>t&&(a=a.slice(0,t),u++),{sign:s,digits:a.replace(/0+$/,"")||"0",point:u}}function dt({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 mt(e){let n=0n,t=0n,s=e.d;for(;s%2n==0n;)s/=2n,n++;for(;s%5n==0n;)s/=5n,t++;const i=n>t?n:t;let r=et(e.n)*10n**i/e.d;if(0n===r)return 1;for(;r%10n==0n;)r/=10n;return r.toString().length}function gt(e){let n=e.d;for(;n%2n==0n;)n/=2n;for(;n%5n==0n;)n/=5n;return 1n===n}function vt(e){const n=/^(-?[\d.]+)e(-?\d+)$/.exec(e);return n?N("*",[$(n[1]),N("^",[$("10"),$(n[2])])]):$(e)}function bt(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 s=n+25,i=null;for(let r=0;r<4;r++){const o=new nt(s),a=ct(e,o,t);if(a.z){const e=yt(a.z,o,n);if(e.retry&&r<3){s+=e.retry;continue}return void 0===e.real?e:wt(e.real,o,n,null)}if(a.q&&a.q.isInteger&&et(a.q.n).toString().length<=n)return{text:a.q.n.toString(),node:$(a.q.n.toString()),number:Number(a.q.n),re:Number(a.q.n),im:0,exact:!0};const u=ut(o,a);if(0n===u&&(!a.q||!a.q.isZero)&&r<3){i=null,s*=4;continue}const l=ht(u,o,n);if(i&&l.point<-10&&i.point-l.point>=(s-i.P)/2)return{text:"0",node:$("0"),number:0,re:0,im:0,exact:!1};if(!(l.point<-10&&r<3)||i&&i.point===l.point)return wt(u,o,n,a.q);i={point:l.point,P:s},s+=10-l.point}throw new D("could not approximate")}function wt(e,n,t,s){const i=dt(ht(e,n,t));return{text:i,node:vt(i),number:Number(i),re:Number(i),im:0,exact:Boolean(s)&&gt(s)&&mt(s)<=t}}function yt([e,n],t,s){const i=10n**BigInt(Math.max(0,t.P-s-12)),r=e=>et(e)>i;if(!r(n))return{real:e};const o=ht(n,t,s);if(o.point<-10&&r(n))return{retry:10-o.point};const a=dt(o),u="1"===a?"i":"-1"===a?"-i":`${a}i`,l="1"===a?k("i"):N("*",[vt(a.replace(/^-/,"")),k("i")]);if(!r(e))return{text:u,node:a.startsWith("-")?N("neg",[l]):l,number:NaN,re:0,im:Number(a),exact:!1};const c=dt(ht(e,t,s)),f=a.startsWith("-"),p="1"===a.replace(/^-/,"")?k("i"):N("*",[vt(a.replace(/^-/,"")),k("i")]);return{text:`${c} ${f?"-":"+"} ${u.replace(/^-/,"")}`,node:N(f?"-":"+",[vt(c),p]),number:NaN,re:Number(c),im:Number(a),exact:!1}}function xt(e,n={}){const t=e=>(e=>0===Pe(e).size)(e)?"num"===e.type&&/^-?\d+$/.test(e.token)?e:bt(e,n).node:I(e)?N(e.op,e.args.map(t)):e;return t(e)}const qt={variable:null},kt=(e,n)=>null!==n&&Pe(e).has(n);function $t(e){if("num"===e.type)return L(e.token);if(I(e)&&"/"===e.op&&e.args.every(e=>"num"===e.type)){const n=L(e.args[0].token),t=L(e.args[1].token);return n&&t&&!t.isZero?n.div(t):null}return null}const St=e=>0===Pe(e).size;function Mt(e,n,t){const s=function(e){const n=ze(e);return"num"===n.k?n.q.isZero?n.q:null:"atom"===n.k&&"sym"===n.node.type&&"pi"===n.node.token?L("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(!s)return!1;const[i,r="1"]=String(n).split("/");return t(s.compare(L(i).div(L(r))))}function Nt(e){if(!St(e))return NaN;try{const{number:n}=bt(e,{digits:30});return Math.sign(n)}catch{return NaN}}function Ot(){tn("hasVariable")||(en("hasVariable",e=>kt(e,qt.variable),"mentions the variable being solved for"),en("freeOfVariable",e=>null!==qt.variable&&!kt(e,qt.variable),"does not mention the variable being solved for"),en("isRational",e=>null!==$t(e),"an exact number: 3, -2, 1/2"),en("isWhole",e=>$t(e)?.isInteger??!1,"a whole number (any size)"),en("isEvenWhole",e=>{const n=$t(e);return Boolean(n?.isInteger&&n.n%2n==0n)},"an even whole number"),en("isOddWhole",e=>{const n=$t(e);return Boolean(n?.isInteger&&n.n%2n!=0n)},"an odd whole number"),en("isPositiveRational",e=>($t(e)?.sign??0)>0,"an exact number above 0"),en("isNegativeRational",e=>($t(e)?.sign??0)<0,"an exact number below 0"),en("isConstant",St,"has no unknowns (numbers, π and e only)"),en("notOne",e=>{const n=$t(e);return!n||!n.isOne},"anything except the number 1"),en("notMinusOne",e=>{const n=$t(e);return!n||!n.equals(L("-1"))},"anything except the number -1"),en("hasMinusSign",e=>function(e){const n=ze(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"),en("piMultipleAtLeast",(e,n)=>Mt(e,n,e=>e>=0),"a multiple of π, at least k·π"),en("piMultipleAbove",(e,n)=>Mt(e,n,e=>e>0),"a multiple of π, above k·π"),en("piMultipleBelow",(e,n)=>Mt(e,n,e=>e<0),"a multiple of π, below k·π"),en("piMultipleAtMost",(e,n)=>Mt(e,n,e=>e<=0),"a multiple of π, at most k·π"),en("isPositiveConstant",e=>Nt(e)>0,"no unknowns, and above 0 (e, π, √2, 3)"),en("isNegativeConstant",e=>Nt(e)<0,"no unknowns, and below 0"),en("hasImaginaryPart",e=>{if(!K.complex)return!1;const n=$e(ze(e));return Boolean(n)&&!("num"===n.im.k&&n.im.q.isZero)},"complex mode: has a nonzero imaginary part (unknowns count as real)"),en("isSymbolNode",e=>"sym"===e.type&&!J.has(e.token),"a single unknown such as x"))}function It(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)),s=e=>"sym"===e.type?k(e.token.slice(1)):"num"===e.type?e:N(e.op,e.args.map(s)),i=e=>"sym"===e.type?k(`=${e.token}`):"num"===e.type?e:N(e.op,e.args.map(i)),r=e=>"op"!==e.type?e:t(e)?i(Ze(s(e))):N(e.op,e.args.map(r));return r(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 At(e,n,t,s){return e.explain?e.explain.replace(/\{(\w+)\}/g,(e,i)=>"result"===i?t?s(t):e:n[i]?s(n[i]):e).trim():""}const Et=e=>I(e)&&("+"===e.op||"-"===e.op),Tt=e=>I(e)&&("*"===e.op||"/"===e.op);function*jt(e,n,{order:t="pre"}={}){for(const s of Vn(e,n,{order:t})){const n=Ln(s.rule.outputTemplate,s.bound);yield{rule:s.rule,bound:s.bound,path:s.path,before:s.node,after:n,next:()=>Ze(B(e,s.path,n))}}for(const{node:s,path:i}of C(e,t)){const t=Et(s);if(!t&&!Tt(s))continue;const r=t?Ue(ze(s)):Ve(ze(s));if(r.length<3)continue;const o=t?me:ve;for(let t=0;t<r.length;t++)for(let s=t+1;s<r.length;s++){const a=De(o([r[t],r[s]]));for(const u of Un(a,n)){const n=Ln(u.rule.outputTemplate,u.bound),l=r.filter((e,n)=>n!==t&&n!==s);yield{rule:u.rule,bound:u.bound,path:i,before:a,after:n,next:()=>Ze(B(e,i,De(o([ze(n),...l]))))}}}}}function zt(e,n,{format:t,order:s="pre",maxSteps:i=200,variable:r=null}={}){const o=qt.variable;qt.variable=r;try{let r=Ze(e);const o=new Set([r.s]),a=[];for(let e=0;e<i;e++){let e=null;for(const t of jt(r,n,{order:s})){const n=t.next();if(n.s!==r.s&&!o.has(n.s)){e={c:t,next:n};break}}if(!e)break;const{c:i,next:u}=e;a.push({id:i.rule.id,name:i.rule.name,tags:i.rule.tags,from:r.s,to:u.s,path:i.path,before:i.before.s,after:i.after.s,explanation:At(i.rule,i.bound,Ze(i.after),t)}),r=u,o.add(r.s)}return{node:r,steps:a}}finally{qt.variable=o}}const Zt=(e,n)=>e.length>=n.length&&n.every((n,t)=>e[t]===n),Ct=(e,n)=>{for(const t of e)if(n(t))return t;return null};function Ft(e,n,{diff:t}){let s=null;for(;;){const i=Ct(Vn(e,t,{order:"pre"}),e=>"d-variable"===e.rule.id&&e.path.length>n.length&&Zt(e.path,n));if(!i)break;s=F(e,i.path).args[1],e=Hn(e,i).expr}const i=n.length?n.slice(0,-1):n,r=Rt(F(e,i));return r.s!==F(e,i).s&&(e=i.length?B(e,i,r):r),{expr:e,variable:s}}function Bt(e){if(!I(e))return e;const n=e.args.map(Bt),t=e.op.startsWith("\\:")?e.op.slice(2):null;return t&&d(t)&&h(t).arity===n.length?N(t,n):n.every((n,t)=>n===e.args[t])?e:N(e.op,n)}const Dt=e=>"op"!==e.type&&"1"===e.s,Wt=e=>"op"!==e.type&&"0"===e.s;function Rt(e){if(!I(e))return e;const n=e.args.map(Rt),[t,s]=n;if("*"===e.op&&2===n.length){if(Dt(s))return t;if(Dt(t))return s}if("^"===e.op&&2===n.length&&Dt(s))return t;if("+"===e.op&&2===n.length){if(Wt(s))return t;if(Wt(t))return s}return"-"===e.op&&2===n.length&&Wt(s)?t:n.every((n,t)=>n===e.args[t])?e:N(e.op,n)}function Pt(e,n,{fold:t=null,format:s,maxSteps:i=200,order:r="pre"}={}){let o=e;const a=new Set([o.s]),u=[];for(let e=0;e<i;e++){let e=null;for(const s of Vn(o,n,{order:r})){const n=Hn(o,s);let i=n.expr,r=null;if(t&&({expr:i,variable:r}=Ft(i,s.path,t)),i.s!==o.s&&!a.has(i.s)){e={m:s,a:n,expr:i,variable:r};break}}if(!e)break;const{m:i,a:l,expr:c,variable:f}=e;let p=i.path;for(;;)try{F(c,p);break}catch{p=p.slice(0,-1)}const h=F(c,p);let d=At(i.rule,i.bound,Ze(h),s);f&&d&&!d.endsWith("is 1.")&&(d=d.endsWith(`the derivative of ${s(f)}.`)?`${d.slice(0,-1)}, which is 1.`:`${d} The derivative of ${s(f)} is 1.`),u.push({id:i.rule.id,name:i.rule.name,tags:i.rule.tags,from:o.s,to:c.s,path:p,before:l.before.s,after:h.s,explanation:d}),o=c,a.add(o.s)}return{node:o,steps:u}}const Ut=new Set(["int","der","lim"]),Vt=e=>I(e)&&("+"===e.op||"-"===e.op),Lt=e=>I(e)&&"*"===e.op;function _t(e,n=1,t=[]){return I(e)&&"+"===e.op?(_t(e.args[0],n,t),_t(e.args[1],n,t),t):I(e)&&"-"===e.op&&2===e.args.length?(_t(e.args[0],n,t),_t(e.args[1],-n,t),t):I(e)&&"neg"===e.op?(_t(e.args[0],-n,t),t):(t.push({sign:n,node:e}),t)}const Ht=(e,n=[])=>Lt(e)?(Ht(e.args[0],n),Ht(e.args[1],n),n):(n.push(e),n),Qt=e=>e.reduce((e,n)=>null===e?n.sign<0?N("neg",[n.node]):n.node:N(n.sign<0?"-":"+",[e,n.node]),null),Jt=e=>{try{return ae(ze(e))}catch{return e.s}},Kt=e=>Jt(e.sign<0?N("neg",[e.node]):e.node);function Yt(e,n,t,s=t){const i=e.map((e,n)=>({x:e,i:n,k:t(e)})),r=[];let o=null;for(const e of n){const n=i.findIndex(n=>n.k===s(e));n>=0?(r.push({x:i[n].x,from:e}),i.splice(n,1)):null===o&&(o=r.length,r.push(null))}const a=i.map(e=>({x:e.x,from:null}));return null===o?[...r,...a]:[...r.slice(0,o),...a,...r.slice(o+1)]}function Gt(e,n,{tidy:t=!1}={}){if(!n||e.s===n.s)return n&&e.s===n.s?n:e;if(Vt(e)&&Vt(n)){const s=Yt(_t(e),_t(n),Kt),i=_t(n).filter(e=>!s.some(n=>n.from===e));return Qt(s.map(({x:e,from:n})=>({sign:e.sign,node:Gt(e.node,(n??(1===i.length?i[0]:null))?.node,{tidy:t})})))}if(Vt(e)&&I(n)&&Ut.has(n.op)&&Vt(n.args[0])){const t=e=>I(e.node)&&e.node.op===n.op?Kt({sign:e.sign,node:e.node.args[0]}):Kt(e),s=Yt(_t(e),_t(n.args[0]),t,Kt);return Qt(s.map(({x:e})=>e))}if(Lt(e)&&Lt(n)){if(t)return e;const s=Yt(Ht(e),Ht(n),Jt);return s.map(({x:e,from:n})=>Gt(e,n)).reduce((e,n)=>null===e?n:N("*",[e,n]),null)}if(I(e)&&I(n)&&e.op===n.op&&e.args.length===n.args.length){const s=e.args.map((e,s)=>Gt(e,n.args[s],{tidy:t}));return s.every((n,t)=>n===e.args[t])?e:N(e.op,s)}return e}const Xt=new Set(["normal","normal.collect","normal.expand-collect","simplify.cancel","simplify.expand","cancel","expand","together"]),es=e=>Xt.has(e.id)||(e.tags??[]).includes("tidy");function ns(e,n){if(!e.length)return e;let t=n??A(e[0].from);return e.map(e=>{let n,s=t??A(e.from);try{Jt(A(e.from))!==Jt(t)&&(s=A(e.from)),n=e.to===e.from?s:Gt(A(e.to),s,{tidy:es(e)})}catch(n){if(n instanceof ReferenceError||n instanceof TypeError)throw n;return t=null,e}if(n.s===s.s&&e.to!==e.from&&es(e))return null;t=n;let i=e.path;return e.before&&e.before!==e.from&&(i=function(e,n){const t=Jt(A(n)),s=(e,i)=>{if(e.s===n||Jt(e)===t)return i;if(!I(e))return null;for(let n=0;n<e.args.length;n++){const t=s(e.args[n],i.concat(n));if(t)return t}return null};return s(e,[])}(s,e.before)??null),{...e,from:s.s,to:n.s,path:i}}).filter(Boolean)}const ts={full:[],normal:["hidden","detail"],brief:["hidden","detail","minor","tidy","arithmetic","value"]},ss=(e,n)=>"all"===n||"*"===n||Array.isArray(n)&&n.some(n=>n===e.id||e.tags?.includes(n));function is(e,n,{parse:t,replaceAt:s}){const i=(e,n,t=[])=>{if(e.s===n)return t;if("op"!==e.type)return null;for(let s=0;s<e.args.length;s++){const r=i(e.args[s],n,t.concat(s));if(r)return r}return null},r=(e,n)=>n.reduce((e,n)=>e.args[n],e);let o=n;const a=[];for(const n of e){let e=i(o,n.from);if(!e){try{o=t(n.from)}catch{a.push(n);continue}e=[]}const u=o;if("solve.reject"===n.id){const n=e.slice(0,-1);e.length&&"|"===r(o,n).op&&(o=s(o,n,r(o,n).args[1-e[e.length-1]]))}else if(n.to!==n.from){let i;try{i=t(n.to)}catch{a.push(n);continue}o=e.length?s(o,e,i):i}a.push({...n,from:u.s,to:o.s,path:e.length?[...e,...n.path??[]]:n.path})}return a}const rs=ee(V.ONE),os=(e,n)=>"atom"===e.k&&"sym"===e.node.type&&e.node.token===n;function as(e){switch(e.k){case"num":default:return e;case"atom":return"op"===e.node.type?Te(e.node.op,e.node.args.map(e=>as(ze(e)))):e;case"add":return me(Ue(e).map(as));case"mul":{let n=[ee(e.c)];for(const t of e.fs){const e=as(t.b);if("add"===e.k&&ie(t.e)&&t.e.q.isInteger&&t.e.q.sign>0&&t.e.q.n<=BigInt(60))for(let s=0n;s<t.e.q.n;s++)n=us(n,Ue(e));else n=us(n,[we(e,t.e)])}return me(n)}}}function us(e,n){const t=[];for(const s of e)for(const e of n)t.push(ve([s,e]));return Ue(me(t))}function ls(e,n){const t=new Map;for(const s of Ue(as(e))){const{coef:e,rest:i}=de(s);let r=0;const o=[ee(e)];for(const e of i?Ve(i):[]){const{b:t,e:s}="mul"===e.k&&1===e.fs.length&&e.c.isOne?e.fs[0]:{b:e,e:rs};if(os(t,n)){if(!ie(s)||!s.q.isInteger||s.q.sign<0)return null;r+=Number(s.q.n)}else{if(cs(t,n)||cs(s,n))return null;o.push(e)}}t.set(r,me([t.get(r)??ee(V.ZERO),ve(o)]))}for(const[e,n]of t)ie(n)&&n.q.isZero&&t.delete(e);return t}const cs=(e,n)=>Pe(De(e)).has(n);function fs(e){if(!e)return null;const n=Math.max(0,...e.keys());if(n>256)return null;const t=[];for(let s=0;s<=n;s++){const n=e.get(s)??ee(V.ZERO);if(!ie(n))return null;t.push(n.q)}return t}function ps(e,n){const t=ze(k(n));return me(e.map((e,n)=>ve([ee(e),be(t,ee(V.of(n)))])))}const hs=e=>{const n=e.slice();for(;n.length>1&&n[n.length-1].isZero;)n.pop();return n},ds=(e,n)=>e.reduceRight((e,t)=>e.mul(n).add(t),V.ZERO);function ms(e,n){const t=e.length-1,s=new Array(t);let i=V.ZERO;for(let r=t;r>=1;r--)i=e[r].add(i.mul(n)),s[r-1]=i;return s}function gs(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 s=0;for(;t%e===0n;)t/=e,s++;n.push([e,s])}t>1n&&n.push([t,1]);let s=[1n];for(const[e,t]of n){const n=[];for(const i of s)for(let s=0,r=1n;s<=t;s++,r*=e)n.push(i*r);if(s=n,s.length>2e4)return null}return s.sort((e,n)=>e<n?-1:e>n?1:0)}function vs(e){let n=hs(e);const t=[];for(;n.length>1&&n[0].isZero;)t.push(V.ZERO),n=n.slice(1);if(n.length<=1)return{roots:t,rest:n};const s=n.reduce((e,n)=>e*n.d/U(e,n.d),1n),i=n.map(e=>e.n*s/e.d),r=gs(i[0]),o=gs(i[i.length-1]);if(!r||!o)return{roots:t,rest:n};const a=new Map;for(const e of r)for(const n of o)for(const t of[1n,-1n]){const s=new V(t*e,n);a.set(s.toString(),s)}const u=[...a.values()].sort((e,n)=>e.compare(n));for(const e of u)for(;n.length>1&&ds(n,e).isZero;)t.push(e),n=ms(n,e);return{roots:t.sort((e,n)=>e.compare(n)),rest:n}}function bs(e,n){const t=hs(n);let s=hs(e);const i=t[t.length-1];if(i.isZero)throw new D("division by the zero polynomial");const r=new Array(Math.max(1,s.length-t.length+1)).fill(V.ZERO);for(;s.length>=t.length&&(1!==s.length||!s[0].isZero);){const e=s.length-t.length,n=s[s.length-1].div(i);if(r[e]=n,s=hs(s.map((s,i)=>i>=e&&i-e<t.length?s.sub(n.mul(t[i-e])):s)),s.length-1<e+t.length-1&&s[s.length-1].isZero)break;if(s.length<t.length)break}return{q:hs(r),r:s}}function ws(e){if("num"===e.k)return{coef:e.q,factors:[],notes:[]};if("atom"===e.k)return{coef:V.ONE,factors:[{base:e,exp:rs}],notes:[]};if("mul"===e.k){let n=e.c;const t=[],s=[];for(const i of e.fs)if("add"===i.b.k&&ie(i.e)&&i.e.q.isInteger){const e=ws(i.b);n=n.mul(e.coef.pow(i.e.q.n));for(const n of e.factors)t.push({base:n.base,exp:ve([n.exp,i.e])});s.push(...e.notes)}else t.push({base:i.b,exp:i.e});return ys(n,t,s)}return qs(e)}function ys(e,n,t){const s=new Map;for(const e of n){const n=ae(e.base),t=s.get(n);t?t.exp=me([t.exp,e.exp]):s.set(n,{...e})}return{coef:e,factors:[...s.values()].filter(e=>!(ie(e.exp)&&e.exp.q.isZero)),notes:t}}const xs=e=>de(Ue(e)[0]).coef.sign;function qs(e){const n=Ue(e),t=[],s=n.map(e=>{const{coef:n,rest:t}=de(e);return{coef:n,fs:t?Ve(t).map(ks):[]}}),i=s.reduce((e,n)=>({n:U(e.n,n.coef.n),d:e.d*n.coef.d/U(e.d,n.coef.d)}),{n:0n,d:1n});let r=new V(i.n||1n,i.d);xs(e)<0&&(r=r.neg());const o=[];for(const e of s[0].fs){if(!ie(e.e)){const n=ae(e.b),t=ae(e.e);s.slice(1).every(e=>e.fs.some(e=>ae(e.b)===n&&ae(e.e)===t))&&o.push({base:e.b,exp:e.e});continue}if(e.e.q.sign<=0)continue;let n=e.e.q;const t=ae(e.b);let i=!0;for(const e of s.slice(1)){const s=e.fs.find(e=>ae(e.b)===t&&ie(e.e)&&e.e.q.sign>0);if(!s){i=!1;break}s.e.q.compare(n)<0&&(n=s.e.q)}i&&o.push({base:e.b,exp:ee(n)})}let a=e;if(!r.isOne||o.length){const e=ve([ee(r),...o.map(e=>we(e.base,e.exp))]);a=me(n.map(n=>ve([n,be(e,ee(V.MINUS_ONE))]))),t.push({id:"factor.common",values:{common:e}})}const u="add"===a.k&&ae(a)!==ae(e),l="add"!==a.k?ws(a):u?qs(a):function(e,n){const t=[...$s(e)];for(const s of t){const i=fs(ls(e,s));if(!i||i.length<3)continue;if(1!==t.length)break;const{roots:r,rest:o}=vs(i);if(!r.length)break;const a=[];let u=o[o.length-1]??V.ONE;const l=o.map(e=>e.div(u)),c=[...r].sort((e,n)=>e.abs().compare(n.abs())||n.sign-e.sign);for(const e of c){const t=ps([new V(-e.n),new V(e.d)],s);a.push({base:t,exp:rs}),u=u.div(new V(e.d)),n.push({id:"factor.root",values:{root:ee(e),factor:t}})}if(l.length>1){const e=l.reduce((e,n)=>e*n.d/U(e,n.d),1n),n=l.map(n=>n.mul(new V(e))),t=n.reduce((e,n)=>U(e,n.n),0n)||1n;u=u.mul(new V(t,e)),a.push({base:ps(n.map(e=>e.div(new V(t))),s),exp:rs})}return ys(u,a,[])}const s=Ue(e);if(2===s.length){const[e,t]=s;for(const s of[2,3]){const i=Ss(e,s),r=Ss(Oe(t),s),o=3===s?Ss(t,s):null;if(i&&r&&2===s){n.push({id:"factor.squares",values:{a:i,b:r}});const e=ws(me([i,Oe(r)])),t=ws(me([i,r]));return ys(e.coef.mul(t.coef),[...e.factors,...t.factors],[...e.notes,...t.notes])}if(3===s&&i&&(r||o)){const e=r??o,t=r?-1:1;n.push({id:t<0?"factor.cubes-difference":"factor.cubes-sum",values:{a:i,b:e}});const s=me(t<0?[i,Oe(e)]:[i,e]),a=me([be(i,ee(V.of(2))),t<0?ve([i,e]):Oe(ve([i,e])),be(e,ee(V.of(2)))]),u=ws(s);return ys(u.coef,[...u.factors,{base:a,exp:rs}],u.notes)}}}return{coef:V.ONE,factors:[{base:e,exp:rs}],notes:[]}}(a,t);if(u&&t.length){const e=l.notes.findIndex(e=>"factor.common"===e.id);e>=0&&(t[0].values.common=ve([t[0].values.common,l.notes.splice(e,1)[0].values.common]))}return ys(r.mul(l.coef),[...o,...l.factors],[...t,...l.notes.filter(e=>!t.includes(e))])}const ks=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length?{b:e.fs[0].b,e:e.fs[0].e}:{b:e,e:rs},$s=e=>Pe(De(e));function Ss(e,n){const{coef:t,rest:s}=de(e);if(t.sign<0)return null;const i=function(e,n){const t=e=>{if(e<0n)return null;let t=0n,s=1n;for(;s**BigInt(n)<=e;)s*=2n;for(;t<s-1n;){const i=(t+s)/2n;i**BigInt(n)<=e?t=i:s=i}return t**BigInt(n)===e?t:null},s=t(e.n),i=t(e.d);return null!==s&&null!==i?new V(s,i):null}(t,n);if(!i)return null;const r=[ee(i)];for(const e of s?Ve(s).map(ks):[]){if(!ie(e.e))return null;const t=e.e.q.div(V.of(n));if(!t.isInteger)return null;r.push(we(e.b,ee(t)))}return ve(r)}function Ms({coef:e,factors:n}){const t=[],s=[];for(const e of n){const n=ie(e.exp)&&e.exp.q.sign<0,i=n?ee(e.exp.q.neg()):e.exp,r=De(we(e.base,i));(n?s:t).push(r)}const i=e=>e.reduce((e,n)=>e?N("*",[e,n]):n,null),r=e.n<0n?-e.n:e.n;let o=t.length?i(1n===r?t:[De(ee(new V(r))),...t]):De(ee(new V(r)));return e.n<0n&&(o=N("neg",[o])),1n!==e.d&&s.unshift(De(ee(new V(e.d)))),s.length?N("/",[o,i(s)]):o}function Ns(e){if("mul"!==e.k||!e.fs.some(e=>"add"===e.b.k&&ie(e.e)&&e.e.q.isInteger))return function(e){if("mul"!==e.k)return{num:e,den:rs};const n=[ee(new V(e.c.n))],t=[ee(new V(e.c.d))];for(const s of e.fs)ie(s.e)&&s.e.q.sign<0?t.push(we(s.b,ee(s.e.q.neg()))):n.push(we(s.b,s.e));return{num:ve(n),den:ve(t)}}(e);const n=[ee(new V(e.c.n))],t=[ee(new V(e.c.d))];for(const s of e.fs){const e=ie(s.e)&&s.e.q.sign<0,i=e?ee(s.e.q.neg()):s.e,r="add"===s.b.k&&ie(s.e)&&s.e.q.isInteger?Os(s.b):null;!r||ie(r.den)&&r.den.q.isOne?(e?t:n).push(we(s.b,i)):((e?t:n).push(we(r.num,i)),(e?n:t).push(we(r.den,i)))}return{num:ve(n),den:ve(t)}}function Os(e){if("add"!==e.k)return Ns(e);const n=Ue(e).map(Ns),t=new Map;let s=1n;for(const e of n){const{coef:n,rest:i}=de(e.den);s=s*n.n/U(s,n.n);for(const e of i?Ve(i).map(ks):[]){const n=ae(e.b),s=t.get(n);(!s||ie(e.e)&&ie(s.e)&&e.e.q.compare(s.e.q)>0)&&t.set(n,e)}}const i=ve([ee(new V(s)),...[...t.values()].map(e=>we(e.b,e.e))]);if(ie(i)&&i.q.isOne)return{num:e,den:rs};return{num:as(me(n.map(e=>ve([e.num,i,be(e.den,ee(V.MINUS_ONE))])))),den:i}}function Is(e){const{num:n,den:t}=Os(e);if(ie(t)&&t.q.isOne)return null;const s=ws(t),i=e=>{const n=new Set(e.factors.map(e=>ae(e.base))),t=s.factors.filter(e=>n.has(ae(e.base))),i=[...e.factors,...s.factors.map(e=>({base:e.base,exp:Oe(e.exp)}))];return{...ys(e.coef.div(s.coef),i,[...e.notes,...s.notes]),canceled:t.map(e=>e.base)}},r=i(ws(n)),o="add"===n.k?as(n):n;if(ae(o)===ae(n))return r;const a=i(ws(o));return j(Ms(a))<j(Ms(r))?a:r}const As=(e,n)=>N("=",[e,n]),Es=Ze(N("+",[k("x"),N("neg",[k("x")])])),Ts=e=>I(e)&&"="===e.op;function js(e,n,t,s={}){const i=[],r=(n,t,s,r,o,a={})=>i.push(e.step(n,t,s,r,o,a));r.raw=e=>i.push(e);const o=Ts(n)?n:As(n,Es),a=As(Ze(o.args[0]),Ze(o.args[1]));a.s!==o.s&&r("normal","Work out each side",["tidy","arithmetic"],o,a);const u=[],l=[],c=new Set;u.numeric=c,Ws(e,a,t,s,r,u,l,0);const f=[],p=new Set,h=n=>Pe(n).size&&e.simplify?e.simplify(n,{steps:!1}).result:zt(n,e.set.view("simplify"),{format:e.format}).node,d=new Map;for(const e of u){const n=c.has(e)?e:h(e),s=n.s;if(p.has(s))continue;p.add(s);const i=c.has(e)?null:Fs(o,t,n);i?r("solve.reject","Check the answer",["check"],As(k(t),n),As(k(t),n),{value:n,reason:i}):(u.periodOf?.has(e)&&d.set(n,u.periodOf.get(e)),f.push(n))}if(f.sort(Zs),s.interval){const n=function(e,n,t,[s,i],r,o,a){const u=Ze(e.node(s)),l=Ze(e.node(i)),c=Cs(u),f=Cs(l);if(!c||!f||Math.abs(c.im)>1e-12||Math.abs(f.im)>1e-12)throw new D("the interval is two numbers, lo and hi");if(c.re>f.re)throw new D("the interval starts after it ends");const p=e=>e>=c.re-1e-9&&e<=f.re+1e-9,h=[],d=new Set,m=e=>{d.has(e.s)||(d.add(e.s),h.push(e))};let g=null;for(const e of n){const n=Cs(e);if(!n||Math.abs(n.im)>1e-12)continue;const s=t.get(e);if(void 0===s){p(n.re)&&m(e);continue}if(null===s){g=[o],p(n.re)&&m(e);continue}const i=Cs(s).re,u=Math.ceil((c.re-n.re)/i-1e-9),l=Math.floor((f.re-n.re)/i+1e-9);if(l-u+1>zs)throw new D(`more than ${zs} answers in that interval`);for(let n=u;n<=l;n++){const t=0===n?e:r(De(me([ze(e),ve([ee(V.of(n)),ze(s)])])));Fs(o,a,t)||m(t)}}return h.sort(Zs),{values:h,lo:u,hi:l,uneven:g}}(e,f,d,s.interval,e=>h(e),o,t);return n.uneven&&l.push(...n.uneven),{solutions:n.values,base:f,unsolved:l,steps:i,always:l.some(e=>e.always),periodic:!1,period:null,interval:[n.lo,n.hi]}}const m=u.periods??[],g=f.length&&m.length&&m.every(e=>e&&e.s===m[0].s)?m[0]:null;return{solutions:f,unsolved:l,steps:i,always:l.some(e=>e.always),periodic:m.length>0&&f.length>0,period:g}}const zs=200;function Zs(e,n){const t=Cs(e),s=Cs(n);return null===t||null===s?e.s<n.s?-1:1:(Math.abs(t.im)>0)-(Math.abs(s.im)>0)||t.re-s.re||t.im-s.im}function Cs(e){if(Pe(e).size)return null;try{const{re:n,im:t}=bt(e,{digits:20});return{re:n,im:t}}catch{return null}}function Fs(e,n,t){const[s,i]=e.args,r=new Set([...Pe(s),...Pe(i),...Pe(t)]);if(r.delete(n),r.size)return null;const o=e=>Bs(e,n,t);try{const e=bt(o(s),{digits:40}),n=bt(o(i),{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 Bs(e,n,t){return"sym"===e.type?e.token===n?t:e:I(e)?N(e.op,e.args.map(e=>Bs(e,n,t))):e}const Ds=24;function Ws(e,n,t,s,i,r,o,a){if(a>Ds)return Ys(e,n,t,s,i,r,o);const u=function(e){const n=[],t=e=>{if(I(e)&&"|"===e.op)return void e.args.forEach(t);if(!Ts(e))return void n.push(e);const s=e.args[1],i=C(s,"pre").find(({node:e})=>I(e)&&"pm"===e.op);if(!i)return void n.push(e);const r=i.node.args[0],o=Ze(B(s,i.path,r)),a=Ze(B(s,i.path,N("neg",[r])));t(As(e.args[0],o)),a.s!==o.s&&t(As(e.args[0],a))};return t(e),n}(n);if(u.length>1){i("solve.split","Two cases",["split","minor"],n,u.reduce((e,n)=>e?N("|",[e,n]):n,null));for(const n of u)Ws(e,n,t,s,i,r,o,a+1);return}if(1===u.length&&u[0].s!==n.s)return Ws(e,u[0],t,s,i,r,o,a+1);const[l,c]=n.args;if("sym"===l.type&&l.token===t&&!cs(ze(c),t))return void r.push(c);const f=me([ze(l),Oe(ze(c))]);if(!cs(f,t))return ie(f)&&f.q.isZero?(i("solve.always","Always true",["check"],n,n,{v:t}),void o.push(Object.assign(Object.create(n),{always:!0}))):void i("solve.never","No solution",["check"],n,n,{v:t});const p=Ue(f).filter(e=>cs(e,t)),h=Ue(f).filter(e=>!cs(e,t)),d=me(p),m=Oe(me(h));if(K.complex){const u=ls(f,t);if(u&&[...u.values()].every(e=>!cs(e,t))&&Math.max(...u.keys())>=2){const l=As(De(f),Es);return l.s!==n.s&&i("solve.one-side","Everything on one side",["move","minor"],n,l,{v:t}),_s(e,f,u,t,s,i,r,o,a,l)}}if(1===p.length)return Rs(e,n,d,m,t,s,i,r,o,a);const g=As(De(f),Es),v=ls(f,t);if(v&&[...v.values()].every(e=>!cs(e,t))&&Math.max(...v.keys())>=2)return g.s!==n.s&&i("solve.one-side","Everything on one side",["move","minor"],n,g,{v:t}),_s(e,f,v,t,s,i,r,o,a,g);if(v&&1===Math.max(...v.keys())&&[...v.values()].every(e=>!cs(e,t))){const u=v.get(1),l=ve([u,ze(k(t))]),c=Oe(v.get(0)??ee(V.ZERO)),f=As(De(l),De(c));return i("solve.collect","Collect the terms",["move","minor"],n,f,{v:t,a:De(u)}),Rs(e,f,l,c,t,s,i,r,o,a)}const b=ws(f),w=b.factors.filter(e=>(cs(e.base,t)||cs(e.exp,t))&&!(ie(e.exp)&&e.exp.q.sign<0));if(w.length>=2||1===w.length&&b.factors.length>1){const u=As(Ms(b),Es);g.s!==n.s&&i("solve.one-side","Everything on one side",["move","minor"],n,g,{v:t}),u.s!==g.s&&i("solve.factor","Factor",["factor"],g,u,{});const l=w.filter(e=>Ps(we(e.base,e.exp)));if(l.length){const n=w.filter(e=>!l.includes(e)),c=As(n.length?Ms({coef:V.ONE,factors:n}):De(ee(V.ONE)),Es);return i("solve.never-zero","A factor that is never zero",["move"],u,c,{f:De(ve(l.map(e=>we(e.base,e.exp))))}),n.length?1===n.length?Ws(e,As(De(n[0].base),Es),t,s,i,r,o,a+1):Ws(e,c,t,s,i,r,o,a+1):void i("solve.never","No solution",["check"],c,c,{v:t})}const c=w.map(e=>As(De(e.base),Es));c.length>1&&i("solve.zero-product","A product is zero when a factor is",["split"],u,c.reduce((e,n)=>e?N("|",[e,n]):n,null),{});for(const n of c)Ws(e,n,t,s,i,r,o,a+1);return}const y=Os(f);if(cs(y.den,t)){const u=As(De(y.num),Es);return i("solve.clear-denominator","Clear the denominator",["move"],n,u,{den:De(y.den)}),Ws(e,u,t,s,i,r,o,a+1)}const x=p.filter(e=>!Ls(e,t));if(1===x.length&&/\b(sqrt|root|abs)\b/.test(De(x[0]).s))return Rs(e,n,x[0],Oe(me(Ue(f).filter(e=>e!==x[0]))),t,s,i,r,o,a);const q=function(e,n){let t=null,s=null,i=null;for(const r of Ue(e)){const e=Ve(r).map(De),o=e.filter(e=>cs(ze(e),n));if(1!==o.length||!I(o[0])||!["sin","cos"].includes(o[0].op))return null;const a=o[0].args[0];if(i&&a.s!==i.s)return null;i=a;const u=ve(e.filter(e=>e!==o[0]).map(ze));"sin"===o[0].op?t=t?me([t,u]):u:s=s?me([s,u]):u}return!t||!s||ie(t)&&t.q.isZero?null:{a:t,b:s,u:i}}(f,t);if(q){const u=As(N("tan",[q.u]),De(Oe(Ie(q.b,q.a))));return g.s!==n.s&&i("solve.one-side","Everything on one side",["move","minor"],n,g,{v:t}),i("solve.sin-cos","Divide by the cosine",["trig"],g,u,{u:q.u}),Ws(e,u,t,s,i,r,o,a+1)}const $=function(e,n){const t=De(e),s={sin:new Set,cos:new Set};let i=null,r=!0;const o=(e,t)=>{if(I(e)){if(("sin"===e.op||"cos"===e.op)&&Pe(e).has(n)){i&&e.args[0].s!==i.s&&(r=!1),i=e.args[0];const n=t&&"^"===t.op&&t.args[0]===e?De(ze(t.args[1])):null;return void s[e.op].add(n&&ie(ze(n))&&ze(n).q.isInteger&&ze(n).q.n%2n==0n?"even":"odd")}["tan","sec","csc","cot"].includes(e.op)&&Pe(e).has(n)&&(r=!1);for(const n of e.args)o(n,e)}};if(o(t,null),!(r&&i&&s.sin.size&&s.cos.size))return null;const a=s.cos.has("odd")?s.sin.has("odd")?null:"sin":"cos";if(!a)return null;const u="cos"===a?"sin":"cos",l=e=>{if(!I(e))return e;if("^"===e.op&&I(e.args[0])&&e.args[0].op===a&&e.args[0].args[0].s===i.s){const n=ze(e.args[1]).q.div(V.of(2));return N("^",[N("-",[De(ee(V.ONE)),N("^",[N(u,[i]),De(ee(V.of(2)))])]),De(ee(n))])}return N(e.op,e.args.map(l))};return{E:as(ze(l(t))),u:i,from:a,to:u}}(f,t);if($)return g.s!==n.s&&i("solve.one-side","Everything on one side",["move","minor"],n,g,{v:t}),i("solve.pythagorean","Use sin² + cos² = 1",["trig"],g,As(De($.E),Es),{u:$.u,from:k($.from),to:k($.to),fromName:k("sin"===$.from?"sine":"cosine"),toName:k("sin"===$.to?"sine":"cosine")}),Ws(e,As(De($.E),Es),t,s,i,r,o,a+1);const S=function(e,n){const t=De(e),s=new Map;for(const{node:e}of C(t,"pre"))if(I(e)&&Pe(e).has(n))if("^"!==e.op||Pe(e.args[0]).has(n))(["ln","sqrt","abs"].includes(e.op)&&e.args[0].s===n||["sin","cos","tan"].includes(e.op)&&Pe(e.args[0]).has(n))&&s.set(e.s,e);else{const t=ze(e.args[1]),{coef:i,rest:r}=de(t);if(r&&i.isInteger&&De(r).s===n){const t=De(be(ze(e.args[0]),ze(k(n))));s.set(t.s,t)}}const i="u"===n?"w":"u";for(const e of s.values()){const s=Ks(t,e,n,i);if(!s||Pe(s).has(n))continue;const r=ze(s),o=ls(r,i);if(o&&Math.max(...o.keys())>=1)return{kernel:ze(e),poly:r,symbol:i}}return null}(f,t);if(S){const n=S.symbol;i("solve.substitute","Substitute",["substitute"],g,As(De(S.poly),Es),{u:k(n),kernel:De(S.kernel)});const u=[];Ws(e,As(De(S.poly),Es),n,s,i,u,o,a+1);for(const l of u){const u=As(De(S.kernel),l);i("solve.back","Substitute back",["substitute"],As(k(n),l),u,{u:k(n),kernel:De(S.kernel)}),Ws(e,u,t,s,i,r,o,a+1)}return}return Ys(e,g,t,s,i,r,o)}function Rs(e,n,t,s,i,r,o,a,u,l){let c=As(De(t),De(s));c.s!==n.s&&o("solve.move","Move the terms",["move","minor"],n,c,{v:i});const{coef:f,rest:p}=de(t),h=p?Ve(p):[],d=ve([ee(f),...h.filter(e=>!cs(e,i))]);if(!ie(d)||!d.q.isOne){const e=ve(h.filter(e=>cs(e,i))),n=As(De(e),De(Ie(s,d))),t=ie(d)&&!d.q.isInteger&&(1n===d.q.n||-1n===d.q.n);o(t?"solve.multiply":"solve.divide",t?"Multiply both sides":"Divide both sides",["move","minor"],c,n,{by:De(t?ee(d.q.inv()):d),v:i}),c=n}if("sym"===c.args[0].type&&c.args[0].token===i)return void a.push(c.args[1]);const m=ze(c.args[1]);if(ie(m)&&m.q.isZero){const n=ze(c.args[0]),t=Ve(n).filter(e=>cs(e,i)&&!Us(e)&&!Ps(e)),s=Ve(n).filter(e=>cs(e,i)&&!Us(e)&&Ps(e));if(s.length&&t.length){const n=As(De(ve(t)),Es);return o("solve.never-zero","A factor that is never zero",["move"],c,n,{f:De(ve(s))}),Ws(e,n,i,r,o,a,u,l+1)}if(s.length&&!Ve(n).some(e=>cs(e,i)&&Us(e)))return void o("solve.never","No solution",["check"],c,c,{v:i});if(!t.length&&Ve(n).some(e=>cs(e,i)))return void o("solve.never","No solution",["check"],c,c,{});if(t.length>1||t.length<Ve(n).filter(e=>cs(e,i)).length){const n=t.map(e=>As(De(Vs(e)),Es));o("solve.zero-product","A product is zero when a factor is",["split"],c,n.reduce((e,n)=>e?N("|",[e,n]):n,null),{});for(const t of n)Ws(e,t,i,r,o,a,u,l+1);return}}const g=zt(c,e.set.view("isolate"),{format:e.format,maxSteps:1,variable:i});if(g.steps.length){const n=function(e,n,t,s){const i=(e.tags??[]).find(e=>"period-2pi"===e||"period-pi"===e);if(!i)return;s.periods??=[];const r=n.args[0].args?.[0];let o=null;try{const e=r?ls(as(ze(r)),t):null,n=e&&[...e.keys()].every(e=>0===e||1===e)?e.get(1):null;n&&!cs(n,t)&&ie(n)&&!n.q.isZero&&(o=De(ve([ee(new V("period-2pi"===i?2n:1n,1n).div(n.q.abs())),ze(k("pi"))])))}catch{}return s.periods.push(o),o}(g.steps[0],c,i,a);!function(e,n){for(const t of n)e.raw(t)}(o,g.steps);const t=a.length;if(Ws(e,g.node,i,r,o,a,u,l+1),void 0!==n){a.periodOf??=new Map;for(const e of a.slice(t))a.periodOf.has(e)||a.periodOf.set(e,n)}return}const v=Ve(ze(c.args[0])).filter(e=>cs(e,i)&&Us(e));if(v.length&&(!ie(m)||!m.q.isZero)){const n=be(ve(v),ee(V.MINUS_ONE)),t=As(De(ve([ze(c.args[0]),n])),De(as(ve([m,n]))));return o("solve.clear-denominator","Clear the denominator",["move"],c,t,{den:De(n)}),Ws(e,t,i,r,o,a,u,l+1)}const b=ze(c.args[0]),w=as(b),y=ae(w)!==ae(b)?ls(w,i):null;if(y&&[...y.values()].every(e=>!cs(e,i))&&Ue(w).length>1){const n=As(De(w),c.args[1]);return o("solve.expand","Multiply out",["expand"],c,n,{v:i}),Ws(e,n,i,r,o,a,u,l+1)}return Ys(e,c,i,r,o,a,u)}function Ps(e){const n=De(e);if(!I(n)||"^"!==n.op)return!1;const t=ze(n.args[0]);return"sym"===t.type&&("e"===t.token||"=e"===t.token)||ie(t)&&t.q.sign>0||"e"===De(t).s}const Us=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&ie(e.fs[0].e)&&e.fs[0].e.q.sign<0,Vs=e=>"mul"===e.k&&e.c.isOne&&1===e.fs.length&&ie(e.fs[0].e)&&e.fs[0].e.q.sign>0?e.fs[0].b:e,Ls=(e,n)=>{const t=ls(e,n);return Boolean(t)&&[...t.values()].every(e=>!cs(e,n))};function _s(e,n,t,s,i,r,o,a,u,l){const c=Math.max(...t.keys()),f=fs(t);if(K.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=be(ee(n.abs()),ee(new V(1n,BigInt(c)))),i=[];for(let s=0;s<c;s++){const r=ve([ee(new V(BigInt((n.sign<0?1:0)+2*s),BigInt(c))),ze(k("pi"))]),o=N("*",[De(t),N("+",[N("cos",[De(r)]),N("*",[k("i"),N("sin",[De(r)])])])]);i.push(zt(o,e.set.view("simplify"),{format:e.format}).node)}return r("solve.roots","All n roots",["complex"],l,i.map(e=>As(k(s),e)).reduce((e,n)=>e?N("|",[e,n]):n),{v:s,n:String(c),last:String(c-1),r:De(ee(n))}),void o.push(...i)}if(Qs(t)===c/2&&c>=4)return Js(e,t,c/2,s,i,r,o,a,u,l);if(f){const{roots:t}=vs(f);if(t.length){const t=ws(n),c=As(Ms(t),Es);if(t.factors.length>1||t.factors.some(e=>!(ie(e.exp)&&e.exp.q.isOne))){r("solve.factor","Factor",["factor"],l,c,{});const n=t.factors.filter(e=>cs(e.base,s)).map(e=>As(De(e.base),Es));n.length>1&&r("solve.zero-product","A product is zero when a factor is",["split"],c,n.reduce((e,n)=>e?N("|",[e,n]):n,null),{});for(const t of n)Ws(e,t,s,i,r,o,a,u+1);return}}}const p=Qs(t);if(p>=2&&c>2&&c/p<=4)return Js(e,t,p,s,i,r,o,a,u,l);if(2===c){const e=t.get(2),n=t.get(1)??ee(V.ZERO),i=t.get(0)??ee(V.ZERO),a=me([be(n,ee(V.of(2))),ve([ee(V.of(-4)),e,i])]);if(ie(a)&&a.q.sign<0&&!K.complex)return void r("solve.no-real","No real solutions",["quadratic"],l,l,{D:De(a)});const u=ve([ee(V.of(2)),e]),c=be(a,ee(V.HALF)),f=De(Ie(me([Oe(n),c]),u)),p=De(Ie(me([Oe(n),Oe(c)]),u)),h=f.s===p.s?As(k(s),f):N("|",[As(k(s),f),As(k(s),p)]);return r(K.complex&&ie(a)&&a.q.sign<0?"solve.quadratic-complex":"solve.quadratic","The quadratic formula",["quadratic"],l,h,{a:De(e),b:De(n),c:De(i),D:De(a),root:De(c),v:s}),o.push(f),void(p.s!==f.s&&o.push(p))}return Ys(e,l,s,i,r,o,a)}const Hs=(e,n)=>n?Hs(n,e%n):e,Qs=e=>[...e.keys()].filter(e=>e>0).reduce((e,n)=>Hs(e,n),0);function Js(e,n,t,s,i,r,o,a,u,l){const c="u"===s?"w":"u",f=be(ze(k(s)),ee(V.of(t))),p=me([...n.entries()].map(([e,n])=>ve([n,be(ze(k(c)),ee(V.of(e/t)))])));r("solve.substitute","Substitute",["substitute"],l,As(De(p),Es),{u:k(c),kernel:De(f)});const h=[];Ws(e,As(De(p),Es),c,i,r,h,a,u+1);for(const n of h){const t=As(De(f),n);r("solve.back","Substitute back",["substitute"],As(k(c),n),t,{u:k(c),kernel:De(f)}),Ws(e,t,s,i,r,o,a,u+1)}}function Ks(e,n,t,s){if(e.s===n.s)return k(s);if(!I(e))return e;if("^"===e.op&&"^"===n.op&&e.args[0].s===n.args[0].s){const n=ze(e.args[1]),{coef:i,rest:r}=de(n);if(r&&De(r).s===t&&i.isInteger)return N("^",[k(s),De(ee(i))])}return N(e.op,e.args.map(e=>Ks(e,n,t,s)))}function Ys(e,n,t,s,i,r,o){if(s.approximate){const e="number"==typeof s.approximate?s.approximate:15,o=ze(N("-",[n.args[0],n.args[1]])),a=K.complex?fs(ls(o,t)):null,u=a&&a.length>2?function(e,n){const t=e.length-1,s=e[t],i=e.map(e=>e/s),r=(e,n)=>{let s=1,r=0;for(let o=t-1;o>=0;o--)[s,r]=[s*e-r*n+i[o],s*n+r*e];return[s,r]};let o=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(o=o.map(([n,s],i)=>{let[a,u]=r(n,s);for(let e=0;e<t;e++){if(e===i)continue;const t=n-o[e][0],r=s-o[e][1],l=t*t+r*r;[a,u]=[(a*t+u*r)/l,(u*t-a*r)/l]}return e=Math.max(e,Math.hypot(a,u)),[n-a,s-u]}),e<1e-15)break}const a=e=>Math.abs(e)<1e-12?0:Number(e.toPrecision(n));return o.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=Gs(e);if(0===n)return t;const s=N("*",[Gs(Math.abs(n)),k("i")]);return 0===e?n<0?N("neg",[s]):s:N(n<0?"-":"+",[t,s])})}(a.map(e=>e.toNumber()),Math.min(e,14)):function(e,n,t){const s=ze(N("-",[e.args[0],e.args[1]])),i=De(s),r=e=>{try{return bt(Bs(i,n,Xs(e)),{digits:30}).number}catch{return NaN}},o=[],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],s=a[e+1],i=r(n);const u=r(s);if(Number.isNaN(i)||Number.isNaN(u))continue;if(0===i){o.push(Xs(n));continue}if(i*u>0)continue;for(let e=0;e<200&&s-n>1e-16*Math.abs(n);e++){const e=(n+s)/2,t=r(e);if(Number.isNaN(t))break;i*t<=0?s=e:(n=e,i=t)}const l=(n+s)/2;Math.abs(r(l))<1e-6&&o.push(Xs(Number(l.toPrecision(Math.min(t,15)))))}return o}(n,t,e);for(const e of u)r.numeric?.add(e);return i("solve.numeric","Numeric solutions",["numeric"],n,u.length?u.map(e=>As(k(t),e)).reduce((e,n)=>e?N("|",[e,n]):n):n,{v:t,count:String(u.length)}),void r.push(...u)}i("solve.unsolved","No exact method",["unsolved"],n,n,{v:t}),o.push(n)}const Gs=e=>$(String(e).includes("e")?e.toFixed(20):String(e)),Xs=e=>$(Number.isInteger(e)?String(e):e.toFixed(17)),ei=["first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth"];const ni=()=>$("1"),ti={"<":e=>e<0,">":e=>e>0,"≤":e=>e<=0,"≥":e=>e>=0},si=new Set(["sin","cos","tan","csc","sec","cot"]);function ii(e,n,t,s={}){const i=[],r=[],o=[];let a=n;for(;I(a.args[0])&&ti[a.args[0].op];)o.unshift({op:a.op,right:a.args[1]}),a=a.args[0];const u=[a.args[0],a.args[1],...o.map(e=>e.right)];[a.op,...o.map(e=>e.op)].forEach((e,n)=>r.push({h:Ze(N("-",[u[n],u[n+1]])),op:e}));const l=new Set(r.flatMap(e=>[...Pe(e.h)]));if(l.delete(t),l.size)throw new D(`an inequality in ${t} with other unknowns (${[...l].join(", ")}) can't be charted`);const c=s.interval?s.interval.map(n=>Ze(e.node(n))):null;if(!c&&r.some(e=>C(e.h,"pre").some(({node:e})=>I(e)&&si.has(e.op)&&Pe(e).has(t))))return{pieces:null,steps:i,unsolved:!0};const f=[];for(const{h:e}of r){f.push(e);for(const{node:n}of C(e,"pre"))I(n)&&Pe(n).has(t)&&("/"===n.op&&f.push(n.args[1]),"sqrt"!==n.op&&"ln"!==n.op||f.push(n.args[0]),"root"===n.op&&f.push(n.args[1]),"log"===n.op&&f.push(n.args[1],n.args[0],N("-",[n.args[0],ni()])),["arcsin","arccos","arctanh","arcsec","arccsc"].includes(n.op)&&f.push(N("-",[n.args[0],ni()]),N("+",[n.args[0],ni()])),"arccosh"===n.op&&f.push(N("-",[n.args[0],ni()])),"^"===n.op&&ie(ze(n.args[1]))&&ze(n.args[1]).q.sign<0&&f.push(n.args[0]),"^"===n.op&&ie(ze(n.args[1]))&&!ze(n.args[1]).q.isInteger&&f.push(n.args[0]))}const p=new Map;for(const n of f){const s=js(e,As(n,Es),t,{...c?{interval:c}:{}});if(s.unsolved.length&&!s.always)return{pieces:null,steps:i,unsolved:!0};if(!s.always)for(const e of s.solutions){const n=Cs(e);!n||Math.abs(n.im)>1e-12||p.set(e.s,{node:e,x:n.re})}}let h=[...p.values()].sort((e,n)=>e.x-n.x).filter((e,n,t)=>0===n||Math.abs(e.x-t[n-1].x)>1e-12),d=null;if(c){const[e,n]=c.map(e=>({node:e,x:Cs(e)?.re}));if(!Number.isFinite(e.x)||!Number.isFinite(n.x)||e.x>n.x)throw new D("the interval is two numbers, lo then hi");d={lo:e,hi:n},h=h.filter(t=>t.x>e.x+1e-12&&t.x<n.x-1e-12)}const m=e=>r.every(({h:n,op:s})=>{try{const i=bt(Bs(n,t,$(function(e){return Math.abs(e)>=1e21?BigInt(Math.round(e)).toString():e.toFixed(Math.min(100,Math.max(0,17-Math.floor(Math.log10(Math.abs(e)||1)))))}(e))),{digits:20});return!(!Number.isFinite(i.re)||Math.abs(i.im)>1e-12)&&ti[s](Math.abs(i.re)<1e-30?0:i.re)}catch{return!1}}),g=e=>r.every(({h:n,op:s})=>{try{const i=bt(Ze(Bs(n,t,e.node)),{digits:30});return!(!Number.isFinite(i.re)||Math.abs(i.im)>1e-12)&&ti[s](Math.abs(i.re)<1e-15?0:i.re)}catch{return!1}});if(d)return function(e,n,t,s,i,{lo:r,hi:o},a,u){const l=[r,...i,o],c=l.map(u),f=l.slice(1).map((e,n)=>a((l[n].x+e.x)/2)),p=[];let h=null;for(let e=0;e<l.length;e++){const n=l[e];if(c[e]&&!h?h={lo:n.node,loClosed:!0}:!c[e]&&h&&(p.push({...h,hi:n.node,hiClosed:!1}),h=null),e===l.length-1)break;f[e]?h??={lo:n.node,loClosed:!1}:h&&(p.push({...h,hi:n.node,hiClosed:c[e]}),h=null)}h&&p.push({...h,hi:o.node,hiClosed:c[l.length-1]});for(const e of p)e.lo.s===e.hi.s&&(e.loClosed=!0,e.hiClosed=!0);const d=i.length?i.map(n=>e.format(n.node)).join(", "):"none";return s.push(e.step("solve.sign-chart","A sign chart",["inequality"],n,n,{points:k(d),v:t})),{pieces:p,steps:s,interval:[r.node,o.node]}}(e,n,t,i,h,d,m,g);const v=h.map(e=>e.x),b=[];if(v.length){b.push(v[0]-Math.max(1,Math.abs(v[0])));for(let e=0;e+1<v.length;e++)b.push((v[e]+v[e+1])/2);b.push(v[v.length-1]+Math.max(1,Math.abs(v[v.length-1])))}else b.push(0);const w=b.map(m),y=h.map(g),x=[];let q=null;const S=(e,n)=>{x.push({...q,hi:e,hiClosed:n}),q=null};for(let e=0;e<=h.length;e++){const n=0===e?null:h[e-1].node;if(w[e]?q??={lo:n,loClosed:!1}:q&&S(n,e>0&&y[e-1]),e===h.length)break;const t=h[e];if(y[e]){if(q)continue;w[e+1]?q={lo:t.node,loClosed:!0}:x.push({lo:t.node,hi:t.node,loClosed:!0,hiClosed:!0})}else q&&S(t.node,!1)}q&&S(null,!1);const M=h.length?h.map(n=>e.format(n.node)).join(", "):"none";return i.push(e.step("solve.sign-chart","A sign chart",["inequality"],n,n,{points:k(M),v:t})),{pieces:x,steps:i}}const ri={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};class oi extends Error{}const ai=e=>({fin:e}),ui={bnd:!0},li=e=>({inf:e}),ci=k("∞");function fi(e){try{const n=bt(e,{digits:15});return Math.abs(n.im??0)>1e-12?NaN:n.re??n.number}catch{return NaN}}function pi(e){if(!K.complex)return Number.isFinite(fi(e));try{const n=bt(e,{digits:15});return Number.isFinite(n.re??n.number)&&Number.isFinite(n.im??0)}catch{return!1}}function hi(e,n,t){if(!Number.isFinite(t))return!1;try{const s=bt(Bs(e,n,$(mi(t))),{digits:15});return Math.abs(s.im??0)>1e-12}catch(e){return/not real/.test(e.message)}}function di(e,n,t){return Number.isFinite(t)?fi(Bs(e,n,$(mi(t)))):NaN}function mi(e){const n=Math.min(40,Math.max(0,16-Math.floor(Math.log10(Math.abs(e)||1))));return e.toFixed(n)}function gi(e,n,t,s){const i=vi(t,s).map(t=>di(e,n,t)).filter(Number.isFinite);if(i.length<3)return NaN;const[r,o,a]=i.slice(-3),u=Math.max(1,Math.abs(a));return Math.abs(a-o)<1e-4*u&&Math.abs(o-r)<.01*u?a:NaN}function vi(e,n){if(e.inf)return[100,1e3,1e4,1e5,1e6].map(n=>n*e.inf);const t=fi(e.fin);return[.001,1e-4,1e-5,1e-6,1e-7].map(e=>t+n*e*Math.max(1,Math.abs(t)))}function bi(e,n,t,s){const i=vi(t,s).map(t=>di(e,n,t)).filter(Number.isFinite);if(!i.length)return 0;const r=Math.sign(i[i.length-1]);return i.slice(-3).every(e=>Math.sign(e)===r)?r:0}function wi(e,n,t,s,i=0){const r=[];if(!i&&!s.inf){const[e,i]=[gi(n,t,s,-1),gi(n,t,s,1)];if(Number.isFinite(e)&&Number.isFinite(i)&&Math.abs(e-i)>.001*Math.max(1,Math.abs(e),Math.abs(i)))throw new oi(`from the left it goes to ${+e.toPrecision(6)}, from the right to ${+i.toPrecision(6)}`)}if(!s.inf&&!K.complex)for(const e of i?[i]:[-1,1])if(vi(s,e).every(e=>hi(n,t,e)))throw new oi(`it has no real values ${e<0?"to the left":"to the right"} of ${+fi(s.fin).toPrecision(6)}`);const o=new xi(e,t,s,i,r);let a;try{if(a=o.of(Ze(function(e,n){const{v:t,a:s,side:i}=e,r=s.inf?s.inf:i;if(!r)return n;let o=n;const a=n=>{if(!I(n))return n;const i=n.args.map(a),u=i.some((e,t)=>e!==n.args[t])?N(n.op,i):n;if("abs"!==u.op||!Pe(u.args[0]).has(t))return u;const l=bi(u.args[0],t,s,r);if(!l)return u;const c=l>0?u.args[0]:Ze(N("neg",[u.args[0]])),f=Ze(yi(o,u,c));return e.step("limit.abs","Absolute value",o,f,{inside:u.args[0],abs:u,to:c,sign:l>0?"positive":"negative",where:s.inf?"that far out":"on this side"}),o=f,c};return a(n),o}(o,n)),0),a.bnd)throw new oi("it keeps swinging between bounds")}catch(e){if(e instanceof oi){const e=(s.inf?[s.inf]:i?[i]:[-1,1]).map(e=>gi(n,t,s,e));if(e.every(Number.isFinite)&&e.every(n=>Math.abs(n-e[0])<1e-6*Math.max(1,Math.abs(n))))throw new D(`numbers near the point settle on ${+e[0].toPrecision(6)}: not answered`)}throw e}return function(e,n,t,s,i){const r=s?[s]:t.inf?[-1]:[-1,1];for(const s of r){const r=vi(t,s).map(t=>di(e,n,t)).filter(Number.isFinite);if(r.length<3)continue;const o=r[r.length-1];if(i.inf){if(Math.sign(o)!==i.inf||Math.abs(o)<Math.abs(r[0]))throw new D(`numbers near the point don't go to ${i.inf>0?"∞":"-∞"}: not answered`)}else{const e=fi(i.fin);if(!Number.isFinite(e))continue;const n=r.map(n=>Math.abs(n-e)),t=Math.abs(r[r.length-1]-r[r.length-2]),s=n.every((e,t)=>0===t||e<n[t-1])&&n[n.length-1]<.5*n[0]&&n[n.length-1]<10*t;if(n[n.length-1]>.01*Math.max(1,Math.abs(e))&&!s)throw new D(`numbers near the point go to ${o.toPrecision(6)}, not ${e.toPrecision(6)}: not answered`)}}}(n,t,s,i,a),{value:a,steps:r}}function yi(e,n,t){return e.s===n.s?t:I(e)?N(e.op,e.args.map(e=>yi(e,n,t))):e}class xi{constructor(e,n,t,s,i){Object.assign(this,{cas:e,v:n,a:t,side:s,steps:i}),this.point=t.inf?t.inf>0?ci:k("-∞"):t.fin}step(e,n,t,s,i={}){this.steps.push(this.cas.step(e,n,["limit"],t,s,{v:k(this.v),a:this.point,...i}))}of(e,n){if(n>8)throw new D("this limit went too deep");const{v:t,a:s}=this;if(!Pe(e).has(t))return ai(e);if("sym"===e.type)return s.inf?li(s.inf):ai(s.fin);if(s.inf){const i=fs(ls(ze(e),t));if(i&&i.length>1){const r=i.length-1,o=i[r].sign*(r%2&&s.inf<0?-1:1);return 0===n&&this.step("limit.leading","The leading term",e,Ze(N("*",[De(ee(i[r])),N("^",[k(t),$(String(r))])])),{f:e,lead:Ze(N("*",[De(ee(i[r])),N("^",[k(t),$(String(r))])]))}),li(o)}}if(!s.inf&&0===n){const n=Bs(e,t,s.fin);let i=null;if(pi(n)&&!this.pole(n)&&!qi(n))try{i=Ze(n)}catch{}if(i&&pi(i)){const n=this.cas.simplify(i,{steps:!1}).result;return this.step("limit.substitute","Put the point in",e,n,{f:e}),ai(n)}}if(!I(e))return ai(e);switch(e.op){case"+":case"-":return this.sum(e,n);case"neg":return $i(this.of(e.args[0],n+1));case"*":return this.product(e,n);case"/":return this.quotient(e,e.args[0],e.args[1],n);case"^":return this.power(e,n);default:return this.func(e,n)}}signOf(e){const n=Math.sign(fi(e));if(!n)throw new D(`the sign of ${this.cas.format(e)} is not known`);return n}pole(e){return ki(e).some(e=>I(e)&&ri[e.op]&&this.isExactZero(N(ri[e.op],[e.args[0]])))}isExactZero(e){try{const n=this.cas.simplify(Ze(e),{steps:!1}).result;return O(n)&&0===Number(n.value)}catch{return!1}}sum(e,n){const[t,s]=e.args;let i,r;try{i=this.of(t,n+1),r=this.of(s,n+1)}catch(t){if(!(t instanceof oi))throw t;const s=Os(ze(e)),i=Ze(N("/",[De(s.num),De(s.den)]));if(i.s===e.s)throw t;return this.step("limit.combine","One fraction",e,i,{f:e}),this.of(i,n+1)}const o="-"===e.op?$i(r):r;if(i.bnd||o.bnd)return i.inf||o.inf?i.inf?i:o:ui;if(i.fin&&o.fin)return ai(Ze(N("+",[i.fin,o.fin])));if(i.inf&&o.inf&&i.inf!==o.inf){const i="-"===e.op?s:N("neg",[s]);if([t,s].some(e=>I(e)&&"sqrt"===e.op)||I(s)&&"neg"===s.op&&I(s.args[0])&&"sqrt"===s.args[0].op){const s=Ze(N("/",[N("-",[N("^",[t,$("2")]),N("^",[i,$("2")])]),N("+",[t,i])]));return this.step("limit.conjugate","∞ − ∞: the conjugate",e,s,{f:e}),this.of(s,n+1)}const r=Os(ze(e)),o=Ze(N("/",[De(r.num),De(r.den)]));if(o.s===e.s)throw new D("∞ − ∞ that does not become one fraction");return this.step("limit.combine","∞ − ∞: one fraction",e,o,{f:e}),this.of(o,n+1)}return i.inf?i:o}product(e,n){const[t,s]=e.args,i=this.of(t,n+1),r=this.of(s,n+1),o=e=>e.fin&&Math.abs(fi(e.fin))<1e-300;if(i.bnd||r.bnd){const n=i.bnd?r:i;if(o(n))return this.step("limit.squeeze","The squeeze theorem",e,$("0"),{f:e,bounded:i.bnd?t:s}),ai($("0"));if(n.inf)throw new oi("a growing factor times one that keeps swinging");return ui}if(i.fin&&r.fin)return ai(Ze(N("*",[i.fin,r.fin])));if(o(i)&&r.inf||i.inf&&o(r)){const[r,a]=o(i)?[t,s]:[s,t],u=e=>e.s.split(" ").length,[l,c]=[Ze(N("/",[$("1"),r])),Ze(N("/",[$("1"),a]))],f=u(l)<=u(c)?N("/",[a,l]):N("/",[r,c]);return this.step("limit.zero-times-infinity","0·∞: a quotient",e,f,{f:e}),this.quotient(f,f.args[0],f.args[1],n+1)}const a=e=>e.inf?e.inf:this.signOf(e.fin);return li(a(i)*a(r))}quotient(e,n,t,s){const{v:i,a:r}=this;if(r.inf){const n=this.rational(e,s);if(n)return n}const o=this.of(n,s+1),a=this.of(t,s+1),u=e=>e.fin&&Math.abs(fi(e.fin))<1e-300;if(o.bnd&&a.inf)return this.step("limit.squeeze","The squeeze theorem",e,$("0"),{f:e,bounded:n}),ai($("0"));if(o.bnd&&a.fin&&!u(a))return ui;if(a.bnd)throw new D("a quotient over something that keeps swinging is not worked out here");if(o.inf&&a.inf&&r.inf){const i=this.dividePower(e,n,t,s);if(i)return i}if(a.fin&&!u(a))return o.fin?ai(this.cas.simplify(Ze(N("/",[o.fin,a.fin])),{steps:!1}).result):li(o.inf*this.signOf(a.fin));if(a.inf&&o.fin)return ai($("0"));if(u(a)&&!u(o))return this.blowUp(e);const l=u(o)?"0/0":"∞/∞",c=this.rational(e,s);if(c)return c;const f=Ze(this.cas.differentiate(n,i)),p=Ze(this.cas.differentiate(t,i)),h=Ze(N("/",[f,p]));return this.step("limit.lhopital","L'Hôpital's rule",e,h,{f:e,form:k(l)}),this.of(h,s+1)}dividePower(e,n,t,s){const{v:i,a:r}=this;if(!ki(e).some(e=>I(e)&&(["sqrt","root","sin","cos"].includes(e.op)||"^"===e.op&&!Pe(e.args[1]).size&&!Number.isInteger(fi(e.args[1]))))||this.divided?.has(e.s))return null;const[o,a]=[1e4*r.inf,1e6*r.inf],u=Math.log(Math.abs(di(t,i,a)/di(t,i,o)))/Math.log(100),l=Math.round(2*u)/2;if(!Number.isFinite(u)||Math.abs(u-l)>.05||l<=0||r.inf<0&&!Number.isInteger(l))return null;const c=N("^",[k(i),$(String(l))]),f=e=>{if(I(e)&&("+"===e.op||"-"===e.op))return N(e.op,e.args.map(f));if(I(e)&&"neg"===e.op)return N("neg",[f(e.args[0])]);if(I(e)&&"sqrt"===e.op){const n=N("sqrt",[Ze(N("/",[e.args[0],N("^",[k(i),$(String(2*l))])]))]);return r.inf<0&&l%2?N("neg",[n]):n}return Ze(N("/",[e,c]))},p=N("/",[Ze(f(n)),Ze(f(t))]);return(this.divided??=new Set).add(e.s),this.step("limit.divide-power","Divide by the highest power",e,p,{f:e,power:c}),this.quotient(p,p.args[0],p.args[1],s+1)}rational(e,n){const{v:t,a:s}=this,{num:i,den:r}=Os(ze(e)),o=fs(ls(i,t)),a=fs(ls(r,t));if(!o||!a||a.length<2)return null;if(s.inf){const[n,i]=[o.length-1,a.length-1],r=Ze(N("/",[N("*",[De(ee(o[n])),N("^",[k(t),$(String(n))])]),N("*",[De(ee(a[i])),N("^",[k(t),$(String(i))])])]));if(r.s!==e.s&&this.step("limit.leading","The leading terms",e,r,{f:e,lead:r}),n<i)return ai($("0"));if(n===i)return ai(De(ee(o[n].div(a[i]))));const u=o[n].div(a[i]).sign*((n-i)%2&&s.inf<0?-1:1);return li(u)}const u=this.cas.cancel(e,{steps:!1}).result;if(u.s===e.s)return null;this.step("limit.cancel","Cancel the common factor",e,u,{f:e});const l=Bs(u,t,s.fin);return Number.isFinite(fi(l))?ai(this.cas.simplify(Ze(l),{steps:!1}).result):this.blowUp(u)}blowUp(e){const{v:n,a:t,side:s}=this,i=(s?[s]:[-1,1]).map(s=>bi(e,n,t,s));if(i.includes(0))throw new D("the sign near the point could not be told");if(2===i.length&&i[0]!==i[1])throw this.step("limit.one-sided","The two sides differ",e,e,{f:e,left:i[0]>0?ci:k("-∞"),right:i[1]>0?ci:k("-∞")}),new oi(`from the left it goes to ${i[0]>0?"∞":"-∞"}, from the right to ${i[1]>0?"∞":"-∞"}`);return li(i[0])}power(e,n){const{v:t}=this,[s,i]=e.args,r=this.of(s,n+1);let o;const a=this.steps.length;try{o=this.of(i,n+1)}catch(t){if(!(t instanceof oi)||!r.fin||Math.abs(fi(r.fin)-1)>1e-12)throw t;return this.steps.length=a,this.expLog(e,s,i,"1^∞",n)}if(r.bnd||o.bnd)throw new D("a power of something that keeps swinging is not worked out here");const u=e=>e.fin?fi(e.fin):e.inf*(1/0),l=u(r),c=u(o);if(r.fin&&o.fin){if(Math.abs(l)<1e-300&&c<0)return this.blowUp(e);if(!(Math.abs(l)<1e-300&&Math.abs(c)<1e-300))return ai(this.cas.simplify(Ze(N("^",[r.fin,o.fin])),{steps:!1}).result)}const f=!Pe(s).has(t),p=!Pe(i).has(t),h=r.fin&&Math.abs(l)<1e-300,d=r.fin&&Math.abs(l-1)<1e-12;if(r.fin&&o.inf&&(!d||f)){if(d)return ai($("1"));if(h){if(o.inf<0){if(f)throw new oi("0 to a negative power has no value");return li(1)}return ai($("0"))}if(l>1)return o.inf>0?li(1):ai($("0"));if(l>0)return o.inf>0?ai($("0")):li(1);throw new oi("a negative number to a growing power swings between signs")}if(r.inf<0&&!p)throw new D("a power of something going to -∞ is not worked out here");if(r.inf&&(p||o.fin&&Math.abs(c)>1e-300||o.inf)){if(c>0)return li(r.inf>0?1:p&&Number.isInteger(c)&&c%2?-1:1);if(c<0)return ai($("0"))}if(p&&h&&c>0)return ai($("0"));const m=d?"1^∞":h?"0^0":r.inf&&o.fin?"∞^0":null;if(!m)throw new D("a power of this shape is not worked out here");return this.expLog(e,s,i,m,n)}expLog(e,n,t,s,i){const r=Ze(N("*",[t,N("ln",[n])]));this.step("limit.exp-log","Take logs",e,N("^",[k("e"),r]),{f:e,form:k(s)});const o=this.of(r,i+1);if(o.bnd)throw new D("a power of something that keeps swinging is not worked out here");return o.inf?o.inf>0?li(1):ai($("0")):ai(this.cas.simplify(Ze(N("^",[k("e"),o.fin])),{steps:!1}).result)}func(e,n){const t=e.op,s=e.args;if(1!==s.length){if("log"===t&&!Pe(s[0]).has(this.v)){const e=this.of(s[1],n+1);if(e.fin){const n=Ze(N("log",[s[0],e.fin]));if(Number.isFinite(fi(n)))return ai(this.cas.simplify(n,{steps:!1}).result)}return this.of(Ze(N("/",[N("ln",[s[1]]),N("ln",[s[0]])])),n+1)}throw new D(`a limit of ${t} is not worked out here`)}let i;try{i=this.of(s[0],n+1)}catch(e){if(e instanceof oi&&("sin"===t||"cos"===t))return ui;throw e}if(i.bnd){if("sin"===t||"cos"===t||"arctan"===t||"abs"===t)return ui;throw new D(`${t} of something that keeps swinging is not worked out here`)}if(i.fin){if(ri[t]&&this.isExactZero(N(ri[t],[i.fin])))return this.blowUp(e);const n=Ze(N(t,[i.fin]));if(pi(n))return ai(this.cas.simplify(n,{steps:!1}).result);if("ln"===t&&Math.abs(fi(i.fin))<1e-300)return li(-1);if(["tan","sec","csc","cot"].includes(t))return this.blowUp(e);throw new D(`${t} has no value at the limit of its argument`)}const r=i.inf;switch(t){case"sqrt":case"ln":case"cosh":if(r<0&&"cosh"!==t)throw new oi(`${t} has no value as its argument goes to -∞`);return li(1);case"abs":return li(1);case"sinh":return li(r);case"tanh":return ai($(String(r)));case"arctan":return ai(Ze(N("/",[r>0?k("pi"):N("neg",[k("pi")]),$("2")])));case"arccot":return ai(r>0?$("0"):k("pi"));case"arcsec":case"arccsc":return ai("arcsec"===t?Ze(N("/",[k("pi"),$("2")])):$("0"));case"sin":case"cos":return ui;case"tan":case"sec":case"csc":case"cot":throw new oi(`${t} keeps swinging as its argument grows`);default:throw new D(`a limit of ${t} at ∞ is not worked out here`)}}}const qi=e=>ki(e).some(e=>I(e)&&("/"===e.op&&Math.abs(fi(e.args[1]))<1e-300||"^"===e.op&&fi(e.args[1])<0&&Math.abs(fi(e.args[0]))<1e-300)),ki=(e,n=[])=>(n.push(e),I(e)&&e.args.forEach(e=>ki(e,n)),n),$i=e=>e.bnd?e:e.inf?li(-e.inf):ai(Ze(N("neg",[e.fin])));function Si(e){if(!I(e)||"lim"!==e.op)return null;const[n,t,s,i]=e.args;if(I(t)&&"→"===t.op)return{f:n,v:t.args[0].token,to:t.args[1],side:0};if("sym"===t?.type&&s){const e="r"===i?.token?1:"l"===i?.token?-1:0;return{f:n,v:t.token,to:s,side:e}}return null}function Mi(e){return"sym"!==e.type||"∞"!==e.token&&"oo"!==e.token&&"infinity"!==e.token?"sym"===e.type&&"-∞"===e.token||I(e)&&"neg"===e.op&&"sym"===e.args[0].type&&"∞"===e.args[0].token?li(-1):ai(Ze(e)):li(1)}const Ni=e=>e.inf?e.inf>0?ci:k("-∞"):e.fin,Oi=new Set(["sin","cos","tan","sec","csc","cot"]),Ii=()=>$("2");function Ai(e,n){if(!Ei(n))return[];let t,s;try{const e=ji(n);t=new Map;s=Os(ze(zi(e,t)))}catch{return[]}const i=[],r=Ti(n);for(const n of["sin","cos","none"])try{const o=[as(s.num),as(s.den)],a="none"===n?o[0]:Zi(s.num,t,n),u="none"===n?o[1]:Zi(s.den,t,n);if(!a||!u)continue;const l=De(a).s!==De(o[0]).s||De(u).s!==De(o[1]).s,c=[{p:Bi(a,u),how:l?"pythagorean":r?"expand-double":"sin-cos"}],f=[Ci(a,t),Ci(u,t)];f[0]&&f[1]&&c.push({p:Bi(f[0],f[1]),how:"double-angle"});for(const n of c)i.push({node:Wi(e,Di(n.p,t)),how:n.how})}catch{}return i}const Ei=e=>I(e)&&(Oi.has(e.op)||e.args.some(Ei)),Ti=e=>I(e)&&(("sin"===e.op||"cos"===e.op)&&I(e.args[0])&&"*"===e.args[0].op&&O(e.args[0].args[0])&&2===Number(e.args[0].args[0].value)||e.args.some(Ti));function ji(e){if(!I(e))return e;const n=e.args.map(ji),[t]=n,s=e=>N("sin",[e]),i=e=>N("cos",[e]),r=e=>I(e)&&"*"===e.op&&O(e.args[0])&&2===Number(e.args[0].value)?2===e.args.length?e.args[1]:N("*",e.args.slice(1)):null;switch(e.op){case"tan":return N("/",[s(t),i(t)]);case"sec":return N("/",[$("1"),i(t)]);case"csc":return N("/",[$("1"),s(t)]);case"cot":return N("/",[i(t),s(t)]);case"sin":{const e=r(t);return e?N("*",[N("*",[Ii(),s(e)]),i(e)]):s(t)}case"cos":{const e=r(t);return e?N("-",[N("^",[i(e),Ii()]),N("^",[s(e),Ii()])]):i(t)}default:return N(e.op,n)}}function zi(e,n){if(!I(e))return e;if(("sin"===e.op||"cos"===e.op)&&!Ei(e.args[0])){const t=e.args[0];n.has(t.s)||n.set(t.s,{u:t,s:`$s${n.size}`,c:`$c${n.size}`});const s=n.get(t.s);return k("sin"===e.op?s.s:s.c)}return N(e.op,e.args.map(e=>zi(e,n)))}function Zi(e,n,t){let s=as(e);for(const{s:e,c:i}of n.values()){const[n,r]="sin"===t?[e,i]:[i,e],o=ls(s,n);if(!o)return null;const a=[];for(const[e,t]of o){const s=Math.floor(e/2),i=[t];e%2&&i.push(ze(k(n))),s&&i.push(ze(N("^",[N("-",[$("1"),N("^",[k(r),Ii()])]),$(String(s))]))),a.push(ve(i))}if(s=as(me(a)),Ue(s).length>200)return null}return s}function Ci(e,n){let t=as(e);for(const{u:e,s:s,c:i}of n.values()){const n=N("sin",[N("*",[Ii(),e])]),r=N("cos",[N("*",[Ii(),e])]),o=[];for(const e of Ue(t)){const t=De(e),a=Fi(t,s),u=Fi(t,i);if(a+u===0){o.push(e);continue}if(a+u!==2)return null;const l=Bs(Bs(t,s,$("1")),i,$("1")),c=N("/",1===a?[n,Ii()]:2===a?[N("-",[$("1"),r]),Ii()]:[N("+",[$("1"),r]),Ii()]);o.push(ze(N("*",[l,c])))}t=as(me(o))}return t}function Fi(e,n){const t=ls(ze(e),n);return t?Math.max(0,...t.keys()):0}function Bi(e,n){const t=ze(N("/",[De(e),De(n)])),s=Is(t);return s?Ms(s):De(t)}function Di(e,n){let t=e;for(const{u:e,s:s,c:i}of n.values())t=Bs(Bs(t,s,N("sin",[e])),i,N("cos",[e]));return Ze(t)}function Wi(e,n){const t=e=>{if(!I(e))return e;const n=e.args.map(t);if("/"===e.op&&O(n[0])){const e=n[1],[t,s]=I(e)&&"^"===e.op&&O(e.args[1])?[e.args[0],e.args[1]]:[e,null],i=I(t)&&{cos:"sec",sin:"csc"}[t.op];if(i){const e=N(i,t.args),r=s?N("^",[e,s]):e;return 1===Number(n[0].value)?r:N("*",[n[0],r])}}return N(e.op,n)},s=zt(Ze(t(n)),e.set.view("simplify"),{format:e.format}).node;try{const{num:e,den:n}=Os(ze(s)),t=Ze(N("/",[De(e),De(n)]));return t.s.split(" ").length<s.s.split(" ").length?t:s}catch{return s}}const Ri=(e,n)=>N("int",[e,"string"==typeof n?k(n):n]);function Pi(e,n,t,s=0){if(s>6)throw new D("integration went too deep");const i=[],r=e.set.view("integrate"),o=zt(n,e.set.view("simplify"),{format:e.format});i.push(...Ui(o.steps,e=>Ze(Ri(e,t))));let a=Ze(Ri(o.node,t));for(let n=0;n<40;n++){const n=zt(a,r,{format:e.format});i.push(...n.steps),a=n.node;const t=C(a,"pre").find(({node:e})=>{return I(n=e)&&"int"===n.op&&2===n.args.length;var n});if(!t)return{node:a,steps:i};const o=Vi(e,t.node,s);if(!o)throw new D(`no rule for ∫ ${e.format(t.node.args[0])} d${t.node.args[1].token}`);const u=a;i.push(...Ui(o.steps,e=>Ze(B(u,t.path,e)))),a=Ze(B(a,t.path,o.node))}throw new D("integration did not finish")}function Ui(e,n){return e.map(e=>{const t=n(A(e.from)).s,s=n(A(e.to)).s;return t===e.from&&s===e.to?e:{...e,from:t,to:s,path:null}})}function Vi(e,n,t){const[s,i]=n.args,r=i.token,o=ze(s),a=function(e,n){const{num:t,den:s}=Os(e),i=ws(t),r=ws(s),o=i.coef.div(r.coef);if(o.isOne||!cs(e,n))return null;const a=ve([...i.factors.map(e=>we(e.base,e.exp)),...r.factors.map(e=>we(e.base,Oe(e.exp)))]);return{c:o,rest:a}}(o,r);if(a){const t=N("*",[De(ee(a.c)),Ri(De(a.rest),i)]);return{node:t,steps:[e.step("integrate.constant","Take the number out",["split","minor"],n,t,{c:De(ee(a.c))})]}}const u=Is(o),l=u&&Ms(u);if(l&&j(l)<j(s)&&Pe(l).has(r)){const t=Ri(l,i);return{node:t,steps:[e.step("integrate.cancel","One fraction",["cancel"],n,t,{})]}}const c=Yi(e,n,o,r,!0);if(c)return c;const f=as(o);if(De(f).s!==s.s&&"add"===f.k){const t=Ri(De(f),i);return{node:t,steps:[e.step("integrate.expand","Multiply out",["expand"],n,t,{})]}}const p=function(e,n){const t=new Map;for(const{node:s}of C(e,"pre")){if(!I(s))continue;const e="^"===s.op?s.args:"/"===s.op?[s.args[1]]:"der"===s.op||"int"===s.op?[]:1===s.args.length||"root"===s.op?[s.args[s.args.length-1]]:[];for(const s of e){if("sym"===s.type||!Pe(s).has(n))continue;const e=ls(ze(s),n);if(!e||1!==Math.max(...e.keys()))continue;const i=e.get(1);cs(i,n)||ie(i)&&i.q.isZero||t.set(s.s,{node:s,a:i})}}for(const s of t.values()){if(!Pe(nr(e,s.node,k("§"))).has(n))return s}return null}(s,r);if(p){const i="u"===r?"t":"u",o=nr(s,p.node,k(i));if(!Pe(o).has(r)){const s=Pi(e,Ze(o),i,t+1),a=Ze(Bs(s.node,i,p.node)),u=De(Ie(ze(a),p.a)),l=e=>De(Ie(ze(e),p.a));return{node:u,steps:[e.step("integrate.substitute","Substitute",["substitute"],n,l(Ze(Ri(Ze(o),i))),{u:k(i),inside:p.node,a:De(p.a),v:r,du:Li(e,p.a,r)}),...Ui(s.steps,l),e.step("integrate.back","Substitute back",["substitute"],l(s.node),u,{u:k(i),inside:p.node})]}}}const h=Yi(e,n,o,r);if(h)return h;const d=Ki(e,n,r);if(d)return d;const m=function(e,n,t,s){if(s>=3)return null;const[i,r]=n.args,o="u"===t?"t":"u",a=new Set;for(const{node:r}of C(i,"pre")){if(r===i||!I(r)||r.s===i.s||a.has(r.s)||!Pe(r).has(t)||["der","int"].includes(r.op))continue;let u,l,c;a.add(r.s);try{u=Ze(e.differentiate(r,t))}catch{continue}if(O(u)&&0===Number(u.value))continue;try{l=nr(Ze(N("/",[i,u])),r,k(o))}catch{continue}if(Pe(l).has(t))continue;try{c=Pi(e,Ze(l),o,s+1)}catch{continue}const f=Ze(Bs(c.node,o,r));return{node:f,steps:[e.step("integrate.u-substitution","Substitute",["substitute"],n,Ze(Ri(l,o)),{u:k(o),inside:r,du:u,v:t}),...c.steps,e.step("integrate.back","Substitute back",["substitute"],c.node,f,{u:k(o),inside:r})]}}return null}(e,n,r,t);return m||function(e,n,t,s,i){if(i>=6)return null;const r=Ve(t),o=r.filter(e=>tr(e,s)||!cs(e,s)),a=r.filter(e=>!o.includes(e));if(1!==a.length)return null;const u=ve(o),l=a[0],c=De(l),f=I(c)?c.op:"",p=["ln","arctan","arcsin","arccos","arcsec","arccsc","arccot"];if(!cs(u,s)&&!p.includes(f))return null;let h,d,m;p.includes(f)?(h=l,d=u):(h=u,d=l);try{m=Pi(e,De(d),s,i+1)}catch{return null}const g=ze(e.differentiate(De(h),s)),v=ve([h,ze(m.node)]),b=Ri(De(ve([g,ze(m.node)])),k(s)),w=Ze(N("-",[De(v),b]));return{node:w,steps:[e.step("integrate.parts","Integration by parts",["parts"],n,w,{u:De(h),dv:De(d),V:m.node,du:De(g),v:s})]}}(e,n,o,r,t)}const Li=(e,n,t)=>ie(n)&&n.q.isOne?`d${t}`:ie(n)&&n.q.neg().isOne?`-d${t}`:`${e.format(De(n))} d${t}`,_i=e=>De(ee(e)),Hi=e=>$(String(e));function Qi(e,n){if(!e||!Pe(e).has(n))return null;const t=ls(ze(e),n);if(!t||1!==Math.max(...t.keys()))return null;const s=t.get(1);return!ie(s)||s.q.isZero?null:{a:s.q,node:e}}function Ji(e){return I(e)&&"^"===e.op&&O(e.args[1])&&Number.isInteger(Number(e.args[1].value))?{base:e.args[0],n:Number(e.args[1].value)}:{base:e,n:1}}function Ki(e,n,t){const[s,i]=n.args,r=Ve(ze(s)).map(De).map(Ji),o=(e,...n)=>I(e.base)&&n.includes(e.base.op),a=(s,i,r,o={})=>({node:r,steps:[e.step(s,i,["rewrite"],n,r,{v:t,...o})]});if(2===r.length&&r.every(e=>1===e.n)){const e=r.find(e=>I(e.base)&&"^"===e.base.op&&"sym"===e.base.args[0].type&&"e"===e.base.args[0].token),n=r.find(e=>o(e,"sin","cos")),s=e&&Qi(e.base.args[1],t),i=n&&Qi(n.base.args[0],t);if(s&&i){const[t,r]=[s.a,i.a],o=t.mul(t).add(r.mul(r)),[u,l]=[N("sin",[i.node]),N("cos",[i.node])],c="sin"===n.base.op?N("-",[N("*",[_i(t),u]),N("*",[_i(r),l])]):N("+",[N("*",[_i(t),l]),N("*",[_i(r),u])]);return a("integrate.parts-twice","By parts twice",Ze(N("/",[N("*",[e.base,c]),_i(o)])),{e:e.base,t:n.base})}}if(2===r.length&&r.every(e=>1===e.n&&o(e,"sin","cos")&&Qi(e.base.args[0],t))&&r[0].base.args[0].s!==r[1].base.args[0].s){const[e,n]="sin"===r[0].base.op?r:[r[1],r[0]],[t,s]=[e.base.args[0],n.base.args[0]],o=(e,n)=>N(e,[N(n,[t,s])]);let u;u="sin"===e.base.op&&"cos"===n.base.op?N("+",[o("sin","+"),o("sin","-")]):"cos"===e.base.op?N("+",[o("cos","-"),o("cos","+")]):N("-",[o("cos","-"),o("cos","+")]);return a("integrate.product-to-sum","Product to sum",Ze(Ri(N("/",[u,Hi(2)]),i)))}const u=r.find(e=>o(e,"sin")),l=r.find(e=>o(e,"cos")),c=!u||!l||u.base.args[0].s===l.base.args[0].s;if((u||l)&&c&&r.every(e=>e===u||e===l)&&[u,l].every(e=>!e||e.n>=0))for(const[n,s]of[[l,"sin"],[u,"cos"]]){if(!n||n.n<3||n.n%2==0)continue;const o=n.base.args[0],u=(n.n-1)/2,l=r.filter(e=>e!==n).map(e=>N("^",[e.base,Hi(e.n)])),c=[...l,N("^",[N("-",[Hi(1),N("^",[N(s,[o]),Hi(2)])]),Hi(u)]),N(n.base.op,[o])].reduce((e,n)=>N("*",[e,n])),f=Ze(Ri(c,i)),p=a("integrate.odd-power","An odd power",f,{f:n.base,other:N(s,[o])});if("sym"!==o.type||o.token!==t)return p;const h="u"===t?"t":"u",d=l.length?r.find(e=>e!==n).n:0;if(2*u+d>100)throw new D(`a power this high (${n.n+d}) is not integrated here`);const m="sin"===n.base.op?-1:1,g=N(s,[o]),v=N("*",[N("^",[N("-",[Hi(1),N("^",[k(h),Hi(2)])]),Hi(u)]),N("^",[k(h),Hi(d)])]),b=Ze(Ri(m<0?N("neg",[v]):v,k(h))),w=ls(as(ze(v)),h);if(!w)return p;const y=[...w].map(([e,n])=>N("*",[De(n),N("/",[N("^",[g,Hi(e+1)]),Hi(e+1)])])).reduce((e,n)=>N("+",[e,n])),x=Ze(m<0?N("neg",[y]):y);return{node:x,steps:[...p.steps,e.step("integrate.u-substitution","Substitute",["substitute"],f,b,{u:k(h),inside:g,du:m<0?N("neg",[n.base]):n.base,v:t}),e.step("integrate.back","Back to "+t,["substitute"],b,x,{u:k(h),inside:g})]}}if(1===r.length&&r[0].n>=3&&o(r[0],"sec","csc")&&"sym"===r[0].base.args[0].type&&r[0].base.args[0].token===t){const{base:e,n:n}=r[0],t=e.args[0],s="sec"===e.op?N("tan",[t]):N("cot",[t]),o=N("/",[N("*",[N("^",[e,Hi(n-2)]),s]),Hi(n-1)]),u=N("*",[N("/",[Hi(n-2),Hi(n-1)]),Ri(N("^",[e,Hi(n-2)]),i)]);return a("integrate.reduction","Reduction formula",Ze(N("+",["sec"===e.op?o:N("neg",[o]),u])),{f:e,n:Hi(n)})}const f=e=>{if(!I(e)||"sqrt"!==e.op)return null;const n=ls(ze(e.args[0]),t);if(!n||2!==n.size||!n.has(2)||!n.has(0))return null;const[s,i]=[n.get(2),n.get(0)];return!ie(s)||!ie(i)||s.q.sign>=0||i.q.sign<=0?null:{k:s.q.neg(),c:i.q,root:e}},p=k(t),h=e=>N("sqrt",[_i(e)]),d=f(s),m=I(s)&&"/"===s.op&&O(s.args[0])&&1===s.args[0].value?f(s.args[1]):null;if(d||m){const{k:e,c:n,root:t}=d??m,s=N("arcsin",[N("*",[p,h(e.div(n))])]);return a("integrate.trig-substitution","A trig substitution",Ze(d?N("+",[N("/",[N("*",[p,t]),Hi(2)]),N("*",[N("/",[_i(n),N("*",[Hi(2),h(e)])]),s])]):N("/",[s,h(e)])),{x:p,a:Ze(h(n.div(e)))})}return null}function Yi(e,n,t,s,i=!1){const{num:r,den:o}=Os(t);if(!cs(o,s))return null;const a=fs(ls(r,s)),u=fs(ls(o,s));if(!a||!u||u.length<2)return null;const l=ze(k(s)),c=e=>ps(e,s);if(a.length>=u.length){const{q:t,r:i}=bs(a,u),r=Ri(De(me([c(t),Ie(c(i),c(u))])),k(s));return{node:r,steps:[e.step("integrate.divide","Divide the polynomials",["divide"],n,r,{})]}}if(i)return null;const{roots:f,rest:p}=vs(u),h=new Set(f.map(String)).size===f.length,d=3===p.length&&p[1].mul(p[1]).sub(V.of(4).mul(p[0]).mul(p[2])).sign<0;if(!h||1!==p.length&&!d||!f.length&&!d)return null;const m=(e=>e.length<=1?[V.ZERO]:e.slice(1).map((e,n)=>e.mul(V.of(n+1))))(u),g=f.map(e=>ds(a,e).div(ds(m,e))),v=f.map((e,n)=>Ie(ee(g[n]),me([l,ee(e.neg())])));if(!d){const t=Ri(De(me(v)),k(s));return{node:t,steps:[e.step("integrate.partial-fractions","Partial fractions",["partial-fractions"],n,t,{})]}}let b=a;f.forEach((e,n)=>{b=er(b,Xi(bs(u,[e.neg(),V.of(1)]).q,g[n]))});const w=f.reduce((e,n)=>Gi(e,[n.neg(),V.of(1)]),[V.of(1)]),{q:y}=bs(b,w),[x,q]=[y[0]??V.ZERO,y[1]??V.ZERO],[$,S,M]=bs(u,w).q,O=V.of(4).mul(M).mul($).sub(S.mul(S)),I=ps([$,S,M],s),A=q.div(V.of(2).mul(M)),E=x.sub(q.mul(S).div(V.of(2).mul(M))),T=N("sqrt",[_i(O)]),j=N("*",[_i(A),N("ln",[N("abs",[De(I)])])]),z=N("*",[N("/",[N("*",[Hi(2),_i(E)]),T]),N("arctan",[N("/",[De(ps([S,M.mul(V.of(2))],s)),T])])]),Z=v.length?Ri(De(me(v)),k(s)):Hi(0),C=Ze(N("+",[N("+",[Z,j]),z]));return{node:C,steps:[e.step("integrate.complete-square","Complete the square",["partial-fractions"],n,C,{Q:De(I)})]}}const Gi=(e,n)=>{const t=Array.from({length:e.length+n.length-1},()=>V.ZERO);return e.forEach((e,s)=>n.forEach((n,i)=>{t[s+i]=t[s+i].add(e.mul(n))})),t},Xi=(e,n)=>e.map(e=>e.mul(n)),er=(e,n)=>Array.from({length:Math.max(e.length,n.length)},(t,s)=>(e[s]??V.ZERO).sub(n[s]??V.ZERO));function nr(e,n,t){return e.s===n.s?t:I(e)?N(e.op,e.args.map(e=>nr(e,n,t))):e}const tr=(e,n)=>{const t=ls(e,n);return Boolean(t)&&[...t.values()].every(e=>!cs(e,n))&&Math.max(...t.keys())>=1};function sr(e,n,t,s,i,r){if([s,i].some(e=>Mi(e).inf))return function(e,n,t,s,i,r){const o=[s,i].map(e=>Mi(e)),a=e=>e.inf?e.inf*(1/0):bt(e.fin,{digits:20}).number,[u,l]=o.map(a).sort((e,n)=>e-n);for(const n of r?ir(r,t):[]){let s=[];try{s=e.solve(N("=",[n,$("0")]),t,{steps:!1}).solutions}catch{continue}for(const n of s){const s=bt(n,{digits:20});if(Number.isFinite(s.number)&&!s.im&&s.number>u&&s.number<l)throw new D(`the integrand has no value at ${t} = ${e.format(n)}, between the limits: split the integral there`)}}const c=(s,i,r)=>{if(!i.inf)try{const e=Ze(Bs(n,t,s));if(Number.isFinite(bt(e,{digits:15}).number))return e}catch{}const o=e.limit(n,t,s,{steps:!1,side:i.inf?void 0:r});if(!o.exists)throw new D(`the integral diverges: as ${t} → ${e.format(s)}, ${e.format(n)} has no limit (${o.reason})`);if(o.infinite)throw new D(`the integral diverges: as ${t} → ${e.format(s)}, ${e.format(n)} goes to ${o.text}`);return o.result},f=a(o[0])<a(o[1]),[p,h]=[c(s,o[0],f?"right":"left"),c(i,o[1],f?"left":"right")],d=Ze(N("-",[h,p])),m=N("-",[h,p]);return{value:d,shown:m,step:e.step("integrate.improper","Limits at the ends",["evaluate"],n,m,{a:s,b:i,F:n,v:t})}}(e,n,t,s,i,r);if(r&&!Pe(s).size&&!Pe(i).size){const o=bt(s,{digits:20}).number,a=bt(i,{digits:20}).number,u=[...Pe(r)].filter(e=>e!==t);if(!u.length){const[s,i]=o<=a?[o,a]:[a,o];for(const o of ir(r,t)){let r=[];try{r=e.solve(N("=",[o,$("0")]),t,{steps:!1}).solutions}catch{continue}for(const o of r){const r=bt(o,{digits:20});if(!Number.isFinite(r.number)||r.im||r.number<s||r.number>i)continue;if(r.number>s&&r.number<i)throw new D(`the integrand has no value at ${t} = ${e.format(o)}, between the limits, so F(b) - F(a) would be wrong`);let a=NaN;try{a=bt(Ze(Bs(n,t,o)),{digits:15}).number}catch{}if(!Number.isFinite(a))throw new D(`the integral diverges at ${t} = ${e.format(o)}: F has no value at that limit`)}}}for(let e=0;!u.length&&e<=64;e++){const n=o+(a-o)*(e+.5)/65;try{const e=bt(Bs(r,t,$(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 o=e=>Ze(Bs(n,t,e)),a=Ze(N("-",[o(i),o(s)])),u=N("-",[o(i),o(s)]);return{value:a,shown:u,step:e.step("integrate.evaluate","Between the limits",["evaluate"],n,u,{a:s,b:i,F:n,v:t})}}function ir(e,n){const t=[],s={tan:"cos",sec:"cos",csc:"sin",cot:"sin"};return C(e,"pre").forEach(({node:e})=>{if(!I(e))return;let i=null;"/"===e.op?i=e.args[1]:"^"===e.op&&"num"===e.args[1].type&&e.args[1].value<0||"^"===e.op&&I(e.args[1])&&"neg"===e.args[1].op?i=e.args[0]:s[e.op]&&(i=N(s[e.op],[e.args[0]])),i&&Pe(i).has(n)&&!t.some(e=>e.s===i.s)&&t.push(i)}),t}const rr={"=":1,"≠":1,"<":1,">":1,"≤":1,"≥":1,"+":2,"-":2,"±":2,"*":3,"/":3,neg:4,pm:4,"^":5},or={pi:"π","≤":"≤","≥":"≥"};function ar(e){return pr(e).text}function ur(e,n,t=!1){return e.prec<n||t&&e.prec===n?`(${e.text})`:e.text}const lr=e=>"op"===e.type?e.op:null,cr=e=>e.text.startsWith("-"),fr={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};function pr(e){if("num"===e.type)return{text:e.token,prec:e.token.startsWith("-")?4:9};if("sym"===e.type)return{text:or[e.token]??e.token,prec:9};const n=e.args.map(pr),t=rr[e.op];switch(e.op){case"+":case"-":case"±":{const s="+"===e.op&&["+","-"].includes(lr(e.args[1])),i=cr(n[1])?`(${n[1].text})`:s?n[1].text:ur(n[1],t,!0);return{text:`${ur(n[0],t)} ${"±"===e.op?"±":e.op} ${i}`,prec:t}}case"*":{const s=ur(n[0],t),i=cr(n[1])?`(${n[1].text})`:"*"===lr(e.args[1])?n[1].text:ur(n[1],t,!0);return{text:"num"===e.args[0].type&&"num"!==e.args[1].type&&!/^[\d(-]/.test(i)||"sym"===e.args[1].type&&"i"===e.args[1].token&&!/[\dA-Za-z]$/.test(s)?`${s}${i}`:`${s}·${i}`,prec:t}}case"/":return{text:`${ur(n[0],t)}/${ur(n[1],t,!0)}`,prec:t};case"^":return{text:`${ur(n[0],t+1)}^${ur(n[1],t)}`,prec:t};case"neg":return{text:`-${ur(n[0],3)}`,prec:4};case"pm":return{text:`±${ur(n[0],4)}`,prec:4};case"!":return{text:`${ur(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"op"===e.args[1].type&&"="===e.args[1].op?{text:`d/d${n[1].text.split(" = ")[0]} (${n[0].text}) at ${n[1].text}`,prec:1}:{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:`${ur(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:`${fr[e.op][0]}${n.map(e=>e.text).join(", ")}${fr[e.op][1]}`,prec:9};case"&":return{text:`${n[0].text} and ${n[1].text}`,prec:0};default:return void 0!==t?{text:`${ur(n[0],t)} ${e.op} ${ur(n[1],t,!0)}`,prec:t}:{text:`${e.op.replace(/^\\:?/,"")}(${n.map(e=>e.text).join(", ")})`,prec:9}}}const hr=['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, minor]\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, minor]\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, minor]\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, minor]\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, minor]\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, minor]\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, minor]\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: "Apply the quotient rule: 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: "A natural log differentiates to 1 over {u}, times the derivative of {u}."\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: "A square root differentiates to 1 over twice the square root of {u}, times the derivative 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 negative 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: "Tangent differentiates to 1 over cosine squared of {u}, times the derivative 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 negative 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: "Cotangent differentiates to negative 1 over sine squared of {u}, times the derivative 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: "Inverse sine differentiates to 1 over the square root of 1 minus {u} squared, times the derivative of {u}."\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: "Inverse cosine differentiates to negative 1 over the square root of 1 minus {u} squared, times the derivative of {u}."\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: "Inverse tangent differentiates to 1 over 1 plus {u} squared, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-arcsec\n name: Derivative of arcsecant\n mode: differentiate\n pattern: u arcsec v der\n output: u v der u abs u 2 ^ 1 - sqrt * /\n explain: "Inverse secant differentiates to 1 over the absolute value of {u} times the square root of {u} squared minus 1, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-arccsc\n name: Derivative of arccosecant\n mode: differentiate\n pattern: u arccsc v der\n output: u v der u abs u 2 ^ 1 - sqrt * / neg\n explain: "Inverse cosecant differentiates to negative 1 over the absolute value of {u} times the square root of {u} squared minus 1, times the derivative of {u}."\n tags: [chain, trig]\n\n - id: d-arccot\n name: Derivative of arccotangent\n mode: differentiate\n pattern: u arccot v der\n output: u v der 1 u 2 ^ + / neg\n explain: "Inverse cotangent differentiates to negative 1 over 1 plus {u} squared, times the derivative of {u}."\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: "Hyperbolic tangent differentiates to 1 over hyperbolic cosine squared of {u}, times the derivative 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: "Inverse hyperbolic sine differentiates to 1 over the square root of {u} squared plus 1, times the derivative of {u}."\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: "Inverse hyperbolic cosine differentiates to 1 over the square root of {u} squared minus 1, times the derivative of {u}."\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: "Inverse hyperbolic tangent differentiates to 1 over 1 minus {u} squared, times the derivative of {u}."\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: "A base {a} logarithm differentiates to 1 over {u} times the natural log of {a}, times the derivative of {u}."\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: "Write the root as a power, then bring the power down and drop it by one: the derivative of {u}, over {n} times the same 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: "The variable is in the base and in the exponent, so write {u}^{w} as e to the {w} times the natural log of {u}. By the chain rule, the derivative is the same power, times the derivative of that exponent."\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, minor]\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, minor]\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, minor]\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-sec, name: Integral of sec, mode: integrate, pattern: u sec v 2 int, require: [[sameAs, u, v]], output: v sec v tan + abs ln, tags: [trig], explain: "The derivative of ln|sec {v} + tan {v}| is sec {v}." }\n - { id: i-csc, name: Integral of csc, mode: integrate, pattern: u csc v 2 int, require: [[sameAs, u, v]], output: v csc v cot + abs ln neg, tags: [trig], explain: "The derivative of -ln|csc {v} + cot {v}| is csc {v}." }\n - { id: i-cot, name: Integral of cot, mode: integrate, pattern: u cot v 2 int, require: [[sameAs, u, v]], output: v sin abs ln, tags: [trig], explain: "cot = cos/sin, and ln|sin {v}| differentiates to it." }\n - { id: i-sec-tan, name: Integral of sec·tan, mode: integrate, pattern: u sec u tan * v 2 int, commutative: true, require: [[sameAs, u, v]], output: v sec, tags: [trig], explain: "The derivative of sec {v} is sec {v} tan {v}." }\n - { id: i-csc-cot, name: Integral of csc·cot, mode: integrate, pattern: u csc u cot * v 2 int, commutative: true, require: [[sameAs, u, v]], output: v csc neg, tags: [trig], explain: "The derivative of -csc {v} is csc {v} cot {v}." }\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 # ---- trigonometry: shifts by π/2 and π, written with an unknown angle ----------\n - { id: sin-plus-quarter, name: sin(u + π/2), pattern: u =pi 2 / + sin, commutative: true, output: u cos, tags: [symmetry], explain: "Shifting sine by a quarter turn gives cosine: sin({u} + π/2) = cos {u}." }\n - { id: cos-plus-quarter, name: cos(u + π/2), pattern: u =pi 2 / + cos, commutative: true, output: u sin neg, tags: [symmetry], explain: "cos({u} + π/2) = -sin {u}." }\n - { id: sin-minus-quarter, name: sin(u − π/2), pattern: u =pi 2 / - sin, output: u cos neg, tags: [symmetry], explain: "sin({u} - π/2) = -cos {u}." }\n - { id: cos-minus-quarter, name: cos(u − π/2), pattern: u =pi 2 / - cos, output: u sin, tags: [symmetry], explain: "cos({u} - π/2) = sin {u}." }\n - { id: sin-cofunction, name: sin(π/2 − u), pattern: u neg =pi 2 / + sin, commutative: true, output: u cos, tags: [symmetry], explain: "Sine of the complement is cosine: sin(π/2 - {u}) = cos {u}." }\n - { id: cos-cofunction, name: cos(π/2 − u), pattern: u neg =pi 2 / + cos, commutative: true, output: u sin, tags: [symmetry], explain: "Cosine of the complement is sine: cos(π/2 - {u}) = sin {u}." }\n - { id: tan-cofunction, name: tan(π/2 − u), pattern: u neg =pi 2 / + tan, commutative: true, output: u cot, tags: [symmetry], explain: "tan(π/2 - {u}) = cot {u}." }\n - { id: sin-supplement, name: sin(π − u), pattern: u neg =pi + sin, commutative: true, output: u sin, tags: [symmetry], explain: "sin(π - {u}) = sin {u}." }\n - { id: cos-supplement, name: cos(π − u), pattern: u neg =pi + cos, commutative: true, output: u cos neg, tags: [symmetry], explain: "cos(π - {u}) = -cos {u}." }\n - { id: sin-plus-half, name: sin(u + π), pattern: u =pi + sin, commutative: true, output: u sin neg, tags: [symmetry], explain: "Half a turn changes the sign: sin({u} + π) = -sin {u}." }\n - { id: cos-plus-half, name: cos(u + π), pattern: u =pi + cos, commutative: true, output: u cos neg, tags: [symmetry], explain: "Half a turn changes the sign: cos({u} + π) = -cos {u}." }\n - { id: tan-plus-half, name: tan(u + π), pattern: u =pi + tan, commutative: true, output: u tan, tags: [symmetry], explain: "Tangent repeats every π: tan({u} + π) = tan {u}." }\n - { id: sin-minus-half, name: sin(u − π), pattern: u =pi - sin, output: u sin neg, tags: [symmetry], explain: "sin({u} - π) = -sin {u}." }\n - { id: cos-minus-half, name: cos(u − π), pattern: u =pi - cos, output: u cos neg, tags: [symmetry], explain: "cos({u} - π) = -cos {u}." }\n\n # ---- trigonometry: more exact values (15°, 75°, 22.5°, 67.5°) -------------------\n - { id: sin-pi-12, name: Sine of π/12, pattern: =pi 12 / sin, output: 6 sqrt 2 sqrt - 4 /, tags: [value], explain: "sin(π/12) = sin(π/3 - π/4) = (√6 - √2)/4." }\n - { id: cos-pi-12, name: Cosine of π/12, pattern: =pi 12 / cos, output: 6 sqrt 2 sqrt + 4 /, tags: [value], explain: "cos(π/12) = cos(π/3 - π/4) = (√6 + √2)/4." }\n - { id: tan-pi-12, name: Tangent of π/12, pattern: =pi 12 / tan, output: 2 3 sqrt -, tags: [value], explain: "tan(π/12) = 2 - √3." }\n - { id: sin-5pi-12, name: Sine of 5π/12, pattern: 5 =pi * 12 / sin, output: 6 sqrt 2 sqrt + 4 /, tags: [value], explain: "sin(5π/12) = sin(π/4 + π/6) = (√6 + √2)/4." }\n - { id: cos-5pi-12, name: Cosine of 5π/12, pattern: 5 =pi * 12 / cos, output: 6 sqrt 2 sqrt - 4 /, tags: [value], explain: "cos(5π/12) = cos(π/4 + π/6) = (√6 - √2)/4." }\n - { id: tan-5pi-12, name: Tangent of 5π/12, pattern: 5 =pi * 12 / tan, output: 2 3 sqrt +, tags: [value], explain: "tan(5π/12) = 2 + √3." }\n - { id: sin-pi-8, name: Sine of π/8, pattern: =pi 8 / sin, output: 2 2 sqrt - sqrt 2 /, tags: [value], explain: "By the half-angle formula, sin(π/8) = √(2 - √2)/2." }\n - { id: cos-pi-8, name: Cosine of π/8, pattern: =pi 8 / cos, output: 2 2 sqrt + sqrt 2 /, tags: [value], explain: "By the half-angle formula, cos(π/8) = √(2 + √2)/2." }\n - { id: tan-pi-8, name: Tangent of π/8, pattern: =pi 8 / tan, output: 2 sqrt 1 -, tags: [value], explain: "tan(π/8) = √2 - 1." }\n - { id: sin-3pi-8, name: Sine of 3π/8, pattern: 3 =pi * 8 / sin, output: 2 2 sqrt + sqrt 2 /, tags: [value], explain: "sin(3π/8) = cos(π/8) = √(2 + √2)/2." }\n - { id: cos-3pi-8, name: Cosine of 3π/8, pattern: 3 =pi * 8 / cos, output: 2 2 sqrt - sqrt 2 /, tags: [value], explain: "cos(3π/8) = sin(π/8) = √(2 - √2)/2." }\n - { id: tan-3pi-8, name: Tangent of 3π/8, pattern: 3 =pi * 8 / tan, output: 2 sqrt 1 +, tags: [value], explain: "tan(3π/8) = √2 + 1." }\n\n # ---- trigonometry: a function of an inverse function (a right triangle) -----------\n - { id: sin-arccos, name: sin(arccos u), pattern: u arccos sin, output: u 2 ^ neg 1 + sqrt, tags: [inverse], explain: "In a right triangle with cos θ = {u}, the other side is √(1 - {u}²): sin(arccos {u}) = √(1 - {u}²)." }\n - { id: cos-arcsin, name: cos(arcsin u), pattern: u arcsin cos, output: u 2 ^ neg 1 + sqrt, tags: [inverse], explain: "In a right triangle with sin θ = {u}, cos θ = √(1 - {u}²)." }\n - { id: tan-arcsin, name: tan(arcsin u), pattern: u arcsin tan, output: u u 2 ^ neg 1 + sqrt /, tags: [inverse], explain: "tan(arcsin {u}) = {u}/√(1 - {u}²)." }\n - { id: tan-arccos, name: tan(arccos u), pattern: u arccos tan, output: u 2 ^ neg 1 + sqrt u /, tags: [inverse], explain: "tan(arccos {u}) = √(1 - {u}²)/{u}." }\n - { id: sin-arctan, name: sin(arctan u), pattern: u arctan sin, output: u u 2 ^ 1 + sqrt /, tags: [inverse], explain: "In a right triangle with tan θ = {u}, the long side is √(1 + {u}²): sin(arctan {u}) = {u}/√(1 + {u}²)." }\n - { id: cos-arctan, name: cos(arctan u), pattern: u arctan cos, output: 1 u 2 ^ 1 + sqrt /, tags: [inverse], explain: "cos(arctan {u}) = 1/√(1 + {u}²)." }\n - { id: sec-arctan, name: sec(arctan u), pattern: u arctan sec, output: u 2 ^ 1 + sqrt, tags: [inverse], explain: "sec(arctan {u}) = √(1 + {u}²)." }\n - { id: cos-arcsec, name: cos(arcsec u), pattern: u arcsec cos, output: 1 u /, tags: [inverse], explain: "arcsec {u} is the angle whose cosine is 1/{u}." }\n - { id: sin-arccsc, name: sin(arccsc u), pattern: u arccsc sin, output: 1 u /, tags: [inverse], explain: "arccsc {u} is the angle whose sine is 1/{u}." }\n - { id: tan-arccot, name: tan(arccot u), pattern: u arccot tan, output: 1 u /, tags: [inverse], explain: "arccot {u} is the angle whose tangent is 1/{u}." }\n\n # ---- trigonometry: the angle-sum formulas, read backward -------------------------\n - { id: sin-sum, name: sin(u + v), pattern: u sin v cos * u cos v sin * +, commutative: true, output: u v + sin, tags: [identity], explain: "sin {u} cos {v} + cos {u} sin {v} = sin({u} + {v})." }\n - { id: sin-difference, name: sin(u − v), pattern: u sin v cos * u cos v sin * -, commutative: true, output: u v - sin, tags: [identity], explain: "sin {u} cos {v} - cos {u} sin {v} = sin({u} - {v})." }\n - { id: sin-difference-led-by-minus, name: sin(u − v), pattern: u cos v sin * neg u sin v cos * +, commutative: true, output: u v - sin, tags: [identity], explain: "sin {u} cos {v} - cos {u} sin {v} = sin({u} - {v})." }\n - { id: cos-sum, name: cos(u + v), pattern: u cos v cos * u sin v sin * -, commutative: true, output: u v + cos, tags: [identity], explain: "cos {u} cos {v} - sin {u} sin {v} = cos({u} + {v})." }\n - { id: cos-difference, name: cos(u − v), pattern: u cos v cos * u sin v sin * +, commutative: true, output: u v - cos, tags: [identity], explain: "cos {u} cos {v} + sin {u} sin {v} = cos({u} - {v})." }\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}: {u} is arcsin {r} or π - arcsin {r} (and any whole number of turns, 2πk, more)."\n tags: [inverse, trig, period-2pi]\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}: {u} is ±arccos {r} (and any whole number of turns, 2πk, more)."\n tags: [inverse, trig, period-2pi]\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 ({u} can also be any whole number of half turns, πk, more)."\n tags: [inverse, trig, period-pi]\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'],dr=['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'],mr=new Set(["<",">","≤","≥"]),gr=new Set(["sin","cos","tan","sec","csc","cot"]),vr=new Set(["arcsin","arccos","arctan","arcsec","arccsc","arccot"]),br={normal:"Work out the numbers and collect like terms.","normal.numbers":"Work out the numbers.","normal.collect":"Collect like terms.","normal.expand-collect":"Multiply out the brackets and collect like terms.","solve.both-add":"Add {t} to both sides.","solve.both-subtract":"Subtract {t} from both sides.","solve.both-divide":"Divide both sides by {t}.","solve.both-multiply":"Multiply both sides by {t}.","solve.each-side":"Work out each side.","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: {canceled}.","solve.move":"Keep the terms with {v} on the left and move the others to the right.","solve.collect":"Collect the terms with {v} on the left, where {v} is multiplied by {a} in all, and move the others to the right.","solve.expand":"Multiply out the brackets.","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.back":"Put {kernel} back for {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.interval":"In the interval from {lo} to {hi}, that is {count} answer(s): each one, and the same plus or minus a whole number of periods.","solve.never-zero":"{f} is never 0, so the rest must be: divide both sides by it.","solve.sin-cos":"Divide both sides by cos({u}): sine over cosine is the tangent.","solve.pythagorean":"Write {from}² as 1 - {to}², so there is only {to}({u}).","simplify.trig":"Write it with sin and cos, use sin² + cos² = 1 and the double-angle formulas, and cancel.","simplify.trig.sin-cos":"Write tan, sec, csc and cot with sin and cos, and cancel.","simplify.trig.pythagorean":"Write it with sin and cos, and use sin² + cos² = 1.","simplify.trig.expand-double":"Write the double angles out (sin 2u = 2 sin u cos u, cos 2u = cos²u − sin²u), and cancel.","simplify.trig.double-angle":"Read the double-angle formulas backward: 2 sin u cos u = sin 2u, cos²u − sin²u = cos 2u.","limit.substitute":"{f} is continuous at {v} = {a}: put {a} in.","limit.cancel":"{f} is 0/0 at {v} = {a}: cancel the common factor first.","limit.lhopital":"{f} is {form} as {v} → {a}: by L'Hôpital's rule, take the limit of the top's derivative over the bottom's.","limit.leading":"As {v} → {a}, the highest powers decide: {f} behaves like {lead}.","limit.zero-times-infinity":"{f} is 0·∞: write it as a quotient.","limit.combine":"{f} is ∞ − ∞: write it as one fraction.","limit.squeeze":"{bounded} stays between two bounds, and what it is multiplied by goes to 0: so does the product (the squeeze theorem).","limit.divide-power":"Divide the top and the bottom by {power}.","limit.conjugate":"{f} is ∞ − ∞ with a root: multiply top and bottom by the conjugate.","limit.exp-log":"{f} is {form}: write it as e to the power (exponent · ln base), and find the limit of the exponent.","limit.abs":"{inside} is {sign} {where}, so {abs} is {to}.","limit.one-sided":"From the left {f} goes to {left}, from the right to {right}: the limit does not exist.","solve.sign-chart":"Where each side minus the other is 0, or has no value: {points}. It keeps one sign between them, so test one {v} in each interval, and each point.","solve.unsolved":"There is no exact method here for solving for {v}; try { approximate: true }.","solve.numeric":"Found {count} solution(s) numerically.","system.swap":"Swap the {row} and {other} equations, so that the {row} one has {v} in it.","system.scale":"Divide the {row} equation by {by}, so that {v} stands alone in front.","system.subtract":"Subtract the {from} equation from the {row} one: {v} goes from it.","system.subtract-multiple":"Subtract {k} times the {from} equation from the {row} one: {v} goes from it.","system.add":"Add the {from} equation to the {row} one: {v} goes from it.","system.add-multiple":"Add {k} times the {from} equation to the {row} one: {v} goes from it.","integrate.cancel":"Write the integrand as one fraction and cancel what the top and bottom share.","integrate.expand":"Multiply out, then integrate term by term.","integrate.substitute":"Let {u} = {inside}, so d{u} = {du}.","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.","integrate.improper":"An improper integral: at an infinite end, the limit of {F} as {v} goes there; then subtract.","integrate.u-substitution":"Let {u} = {inside}, so d{u} = {du} d{v}: the integral is in {u} alone.","integrate.complete-square":"Partial fractions, and complete the square in {Q}: the top that is a multiple of its derivative gives a log, the rest an arctangent.","integrate.parts-twice":"By parts twice: the integral of {e}·{t} comes back, so solve for it.","integrate.product-to-sum":"Write the product of sines and cosines as a sum.","integrate.odd-power":"Keep one {f} and write the rest with {other} (sin² + cos² = 1): then {other} is the substitution.","integrate.reduction":"The reduction formula for {f} to the power {n}.","integrate.trig-substitution":"Let {x} = {a}·sin θ: the root becomes {a}·cos θ.",substitute:"Put in the values."},wr=["normal","rewrite","simplify","expand","factor","cancel","diff","differentiate","integrate","solve","solveSystem","substitute","approximate","equivalent","limit"];class yr{constructor(e,n,t,s,i){this.set=e,this.messages=n,this.format=t,this.read=s,this.complex=i;for(const e of wr){const n=yr.prototype[e];this[e]=(...e)=>Y(i,()=>n.apply(this,e))}}node(e){return this.atPoints(this.read_(e))}read_(e){if(e&&"object"==typeof e&&!Array.isArray(e)&&e.type)return e;if(Array.isArray(e))return E(e);if("string"!=typeof e)throw new D("expected an expression");if(this.read){const n=this.read(e);return Array.isArray(n)?E(n):"string"==typeof n?A(n):n}return A(e)}atPoints(e){if(!e||!I(e)||!e.s.includes("= der"))return e;const n=e.args.map(e=>this.atPoints(e)),[t,s]=n;if("der"===e.op&&I(s)&&"="===s.op&&"sym"===s.args[0].type){const e=s.args[0].token;return this.substitute(this.diff(t,e).result,{[e]:s.args[1].s}).result}return N(e.op,n)}step(e,n,t,s,i,r={},o=e){return function(e,n,t,s,i,r,o,a,u=[]){const l=(r??"").replace(/\{(\w+)\}/g,(e,n)=>{const t=o?.[n];return void 0===t?e:"string"==typeof t?t:a(t)});return{id:e,name:n,tags:t,from:s.s,to:i.s,path:u,before:s.s,after:i.s,explanation:l}}(e,n,t,s,i,this.messages[o]??this.messages[e]??"",r,this.format)}select(e,n,t=null){const s=function(e){if(!1===e)return null;if(void 0===e||!0===e)return{show:"all",hide:ts.normal,explain:!0,detail:"normal"};if("string"==typeof e){if(!ts[e])throw new Error(`steps: "${e}" is not one of ${Object.keys(ts).join(", ")}`);return{show:"all",hide:ts[e],explain:!0,detail:e}}const n=e.detail??"normal";if(!ts[n])throw new Error(`steps.detail: "${n}" is not one of ${Object.keys(ts).join(", ")}`);return{show:e.show??"all",hide:[...ts[n],...e.hide??[]],explain:e.explain??!0,detail:n}}(n);return"full"===s?.detail&&(s.split=e=>this.splitTidy(e)),ns(function(e,n){if(!n)return[];e="full"===n.detail?n.split?e.flatMap(n.split):e:function(e){const n=[];for(const t of e){const e=n[n.length-1];if(!("d-variable"===t.id&&e&&/^(\S+) \1 der$/.test(t.before??"")&&` ${e.after??""} `.includes(` ${t.before} `))){n.push(t);continue}const s={...e,to:t.to};if(e.after&&(s.after=` ${e.after} `.replace(` ${t.before} `," 1 ").replace(/ 1 \*(?= )/g,"").trim()),e.explanation){const n=t.before.split(" ")[0],i=` The derivative of ${n} is 1.`;s.explanation=e.explanation.endsWith(`the derivative of ${n}.`)?`${e.explanation.slice(0,-1)}, which is 1.`:e.explanation.endsWith(i)||e.explanation.endsWith(`the derivative of ${n}, which is 1.`)?e.explanation:`${e.explanation}${i}`}n[n.length-1]=s}return n}(e);const t=[];let s=null;for(const i of e){if(!ss(i,n.show)||ss(i,n.hide)){s=s??{from:i.from,ids:[]},s.ids.push(i.id);continue}const e={...i};s&&(e.from=s.from,e.also=s.ids,e.path=null,s=null),!0===n.explain||!1!==n.explain&&ss(i,n.explain)||delete e.explanation,t.push(e)}if(s&&t.length){const n=t[t.length-1];n.to=e[e.length-1].to,n.also=[...n.also??[],...s.ids]}return t}(e,s),t)}splitTidy(e){if(["solve.move","solve.divide","solve.multiply"].includes(e.id))return this.splitBothSides(e);if("normal"!==e.id)return[e];let n,t;try{n=A(e.from),t=_n(n)}catch{return[e]}return t.s===n.s||t.s===e.to?[e]:[this.step("normal.numbers","Work out the numbers",["arithmetic"],n,t),{...this.step("normal.collect","Collect like terms",["tidy"],t,A(e.to),{},C(t,"pre").some(({node:e})=>I(e)&&"*"===e.op&&e.args.some(e=>I(e)&&("+"===e.op||"-"===e.op)))?"normal.expand-collect":"normal.collect"),path:e.path}]}splitBothSides(e){try{return this.bothSides(e)}catch{return[e]}}bothSides(e){let n,t;try{n=A(e.from),t=A(e.to)}catch{return[e]}const s=e.path??[],i=(e,n)=>n.reduce((e,n)=>e?.args?.[n],e),r=i(n,s),o=i(t,s);if(!r||!o||"="!==r.op||"="!==o.op)return[e];const a=e=>s.length?B(n,s,e):e,[u,l]=r.args,[c,f]=o.args,p=[];let h=n;const d=(e,n,t,i)=>{const r=a(n);p.push({...this.step(e,"The same on both sides",["move"],h,r,{t:i}),path:s}),h=a(t),p.push({...this.step("solve.each-side","Work out each side",["arithmetic"],r,h),path:s})};if("solve.move"===e.id){const n=ze(N("-",[u,c]));if(ae(n)!==ae(ze(N("-",[l,f])))||ie(n)&&n.q.isZero)return[e];const t=Ue(n).sort((e,n)=>Number(Pe(n).size>0)-Number(Pe(e).size>0));let s=u,i=l;t.forEach((e,n)=>{const r=ie(e)?e.q.sign>0:!De(e).s.endsWith(" neg"),a=De(r?e:Oe(e)),u=N("=",[N(r?"-":"+",[s,a]),N(r?"-":"+",[i,a])]),l=n===t.length-1?o:N("=",[Ze(u.args[0]),Ze(u.args[1])]);d(r?"solve.both-subtract":"solve.both-add",u,l,a),[s,i]=l.args})}else{const n=ze(N("/",[u,c])),t=e=>{const n=ze(e);return ie(n)&&n.q.isZero};if(!(!(!t(l)||!t(f))||!t(f)&&ae(n)===ae(ze(N("/",[l,f]))))||Pe(n).size||ie(n)&&n.q.isZero)return[e];const s=ie(n)&&!n.q.isInteger&&(1n===n.q.n||-1n===n.q.n),i=De(s?Ie(ze(k("1")),n):n);d(s?"solve.both-multiply":"solve.both-divide",N("=",[N(s?"*":"/",[u,i]),N(s?"*":"/",[l,i])]),o,i)}return p.length&&p.at(-1).to===e.to?p:[e]}result(e,n,t,s={},i=null){let r=e;if(t.approximate&&r){r=xt(r,{digits:"number"==typeof t.approximate?t.approximate:15})}return{result:r,text:r?this.format(r):"",steps:this.select(n,t.steps,i),...s}}variable(e,n){if(n&&!/^\\?[A-Za-z\u0370-\u03FF][A-Za-z0-9_\u0370-\u03FF′]*$/.test(n))throw new D(`"${n}" is not a variable name; for a derivative at a point write der(f, x = a)`);if(n)return n;const t=[...Pe(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 Ze(this.node(e))}rewrite(e,n,t={}){const s=this.node(e),i=this.set.view(n);if(!i.size)throw new D(`no rules in mode "${n}" (modes: ${this.set.modes().join(", ")})`);const r=zt(s,i,{format:this.format,order:t.order,variable:t.variable});return this.result(r.node,[...this.tidyStep(s,Ze(s)),...r.steps],t,{},s)}simplify(e,n={}){const t=this.node(e),s=[...this.tidyStep(t,Ze(t))],i=zt(t,this.set.view("simplify"),{format:this.format});s.push(...i.steps);let r=i.node;const o=ze(r),a=[],u=0===Pe(r).size,l=u?null:Is(o);l&&a.push({node:Ms(l),id:"simplify.cancel",name:"Cancel"});const c=zt(De(as(o)),this.set.view("simplify"),{format:this.format});a.push({node:c.node,id:"simplify.expand",name:"Multiply out"}),"add"!==o.k||u||a.push({node:Ms(ws(o)),id:"simplify.factor",name:"Factor"});const f=e=>C(e,"pre").some(({node:e})=>I(e)&&gr.has(e.op)&&C(e.args[0],"pre").some(({node:e})=>I(e)&&vr.has(e.op)));for(const e of Ai(this,r))a.push({node:e.node,id:"simplify.trig",wording:`simplify.trig.${e.how}`,name:"Trigonometric identities",prefer:f(r)&&!f(e.node)});let p=!1;for(const e of a)p&&"simplify.trig"===e.id&&!e.prefer||(e.prefer&&(p=!0),(j(e.node)<j(r)||e.prefer)&&(s.push(this.step(e.id,e.name,["shorter"],r,e.node,{},e.wording)),r=e.node));return this.result(r,s,n,{},t)}expand(e,n={}){const t=this.node(e),s=De(as(ze(t)));return this.result(s,t.s===s.s?[]:[this.step("expand","Multiply out",["expand"],t,s)],n,{},t)}factor(e,n={}){const t=this.node(e),s=ws(ze(t)),i=Ms(s),r=[],o=s.notes.find(e=>"factor.common"===e.id);return i.s!==Ze(t).s&&r.push(this.step(o?"factor.common":"factor","Factor",["factor"],t,i,o?{common:De(o.values.common)}:{})),this.result(i,r,n,{},t)}cancel(e,n={}){const t=this.node(e),s=ze(t),i=Is(s);if(!i)return this.result(Ze(t),this.tidyStep(t,Ze(t)),n,{},t);const r=Ms(i),o=Os(s),a=N("/",[De(o.num),De(o.den)]),u=[];return"/"===t.op&&a.s===Ze(t).s||u.push(this.step("together","One fraction",["together"],t,a)),r.s!==a.s&&u.push(this.step("cancel","Cancel",["cancel"],a,r,{canceled:i.canceled.length?i.canceled.map(e=>this.format(De(e))).join(", "):"numbers"})),this.result(r,u,n,{},t)}diff(e,n,t={}){const s=this.node(e),i=this.variable(s,n),r="string"==typeof t.steps?t.steps:t.steps?.detail,o=Bt(s),a={diff:this.set.view("differentiate"),simp:this.set.view("simplify")};let u=o;const l=[];for(let e=0;e<(t.order??1);e++){const e=Pt(N("der",[u,k(i)]),a.diff,{fold:"full"===r?null:a,format:this.format}),n=Pt(e.node,a.simp,{format:this.format,order:"post",maxSteps:40}),t=Ze(n.node),s=zt(t,a.simp,{format:this.format});l.push(...e.steps,...n.steps,...this.tidyStep(n.node,t),...s.steps),u=s.node}const c=ze(u),f=Pe(u).size?Is(c):null,p=[f&&{node:Ms(f),id:"simplify.cancel",name:"Cancel"},{node:De(as(c)),id:"simplify.expand",name:"Multiply out"}].find(e=>e&&j(e.node)<j(u));return p&&(l.push(this.step(p.id,p.name,["shorter"],u,p.node)),u=p.node),this.result(u,l,t,{variable:i},N("der",[s,k(i)]))}differentiate(e,n){const t=zt(N("der",[e,k(n)]),this.set.view("differentiate"),{format:this.format,order:"pre"});return zt(t.node,this.set.view("simplify"),{format:this.format}).node}integrate(e,n,t={}){n&&"object"==typeof n&&(t=n,n=void 0);let s=this.node(e);const i=s,r=e=>void 0===e?null:this.node("number"==typeof e?String(e):e);let o=r(t.from),a=r(t.to);if(I(s)&&"int"===s.op){const[e,t,i,r]=s.args;n=t.token,i&&r&&(o=i,a=r),s=e}const u=this.variable(s,n),l=Pi(this,s,u),c=zt(l.node,this.set.view("simplify"),{format:this.format}),f=[...l.steps,...c.steps];if(o&&a){const e=sr(this,c.node,u,o,a,s);f.push(e.step);const n=zt(e.value,this.set.view("simplify"),{format:this.format});return f.push(...this.tidyStep(e.shown,e.value),...n.steps),this.result(n.node,f,t,{antiderivative:c.node,variable:u},I(i)&&"int"===i.op?i:null)}let p=c.node;if(t.constant){const e=new Set([...Pe(s),u]);p=N("+",[p,k(!0===t.constant?["C","c","K"].find(n=>!e.has(n))??"C":String(t.constant))])}return this.result(p,f,t,{variable:u},I(i)&&"int"===i.op?i:N("int",[i,k(u)]))}solve(e,n,t={}){const s=this.node(e),i=this.variable(s,n);if(I(s)&&mr.has(s.op))return this.inequality(s,i,t);const r=js(this,s,i,t);let o=r.solutions;if(t.approximate){const e="number"==typeof t.approximate?t.approximate:15;o=o.map(n=>xt(n,{digits:e}))}const a=e=>e.length?e.map(e=>N("=",[k(i),e])).reduce((e,n)=>e?N("|",[e,n]):n,null):null,u=(r.base??o).map(e=>N("=",[k(i),e])),l=a(r.base??o),c=is(r.steps,s,{parse:A,replaceAt:B}),f=e=>I(e)&&"|"===e.op?e.args.flatMap(f):[e.s],p=c[c.length-1];if(p&&l&&!t.approximate){let e=null;try{e=A(p.to)}catch{}if(e&&e.s!==l.s&&f(e).sort().join("\n")===f(l).sort().join("\n"))p.to=l.s;else if(e&&e.s!==l.s){const n=e=>I(e)&&"|"===e.op?e.args.flatMap(n):[e],t=n(e);t.length>=u.length&&t.every(e=>I(e)&&"="===e.op&&e.args[0].s===i)&&c.push(this.step("normal","Work out and collect",["tidy","arithmetic"],e,l))}}const h=r.base?a(o):l;if(r.base&&l&&!t.approximate){const e=c.length?A(c[c.length-1].to):l;h&&h.s===e.s||c.push(this.step("solve.interval","The answers in the interval",["interval"],e,h??e,{lo:r.interval[0],hi:r.interval[1],v:k(i),count:String(o.length)}))}return r.steps=c,{solutions:o,result:h,variable:i,text:r.always?`true for every ${i}`:h?this.format(h):r.unsolved.length?`no exact solution found for ${i}`:"no solution",unsolved:r.unsolved.filter(e=>!e.always),always:r.always,periodic:Boolean(r.periodic),period:r.period??null,...r.interval?{interval:r.interval}:{},steps:this.select(r.steps,t.steps,s)}}inequality(e,n,t){const s=ii(this,e,n,t),i={solutions:[],variable:n,unsolved:[],always:!1,steps:this.select(s.steps,t.steps,e)};if(!s.pieces)return{...i,pieces:null,intervals:"",result:null,unsolved:[e],text:`no exact solution found for ${n}`};const r=k(n),o=1===s.pieces.length&&!s.pieces[0].lo&&!s.pieces[0].hi,a=s.pieces.map(({lo:e,hi:n,loClosed:t,hiClosed:s})=>e&&n&&e.s===n.s?N("=",[r,e]):e||n?e?n?N(s?"≤":"<",[N(t?"≤":"<",[e,r]),n]):N(t?"≥":">",[r,e]):N(s?"≤":"<",[r,n]):null).filter(Boolean).reduce((e,n)=>e?N("|",[e,n]):n,null),u=s.pieces.length?s.pieces.map(({lo:e,hi:n,loClosed:t,hiClosed:s})=>e&&n&&e.s===n.s?`{${this.format(e)}}`:`${t?"[":"("}${e?this.format(e):"-∞"}, ${n?this.format(n):"∞"}${s?"]":")"}`).join(" ∪ "):"∅",l=o?`true for every ${n}`:a?this.format(a):"no solution";return{...i,pieces:s.pieces,intervals:u,result:a,always:o,text:l}}limit(e,n,t,s={}){null==t||"object"!=typeof t||Array.isArray(t)||t.type||(s=t,t=void 0);const i=this.node(e),r=Si(i);if(!r&&C(i,"pre").some(({node:e})=>Si(e))){let e=i;for(const{node:n,path:t}of C(i,"post").filter(({node:e})=>Si(e)).reverse()){const s=this.limit(n,void 0,void 0,{steps:!1});if(!s.exists)return s;if(s.infinite)throw new D("a limit inside an expression that is infinite is not worked out here");e=B(e,t,s.result)}return{...this.simplify(e,s),exists:!0,infinite:!1}}const o=r?r.f:i,a=r?r.v:this.variable(i,n),u=r?r.to:"number"==typeof t?$(String(t)):this.node(t??"0"),l="right"===s.side||"+"===s.side?1:"left"===s.side||"-"===s.side?-1:r?r.side:0;try{const{value:e,steps:n}=wi(this,o,a,Mi(u),l);return{...this.result(Ni(e),is(n,Ze(o),{parse:A,replaceAt:B}),s),exists:!0,infinite:Boolean(e.inf)}}catch(e){if(!(e instanceof oi))throw e;const n={result:null,text:"does not exist",exists:!1,reason:e.message,steps:[]};if(!l&&!Mi(u).inf){const e=e=>{try{return Ni(wi(this,o,a,Mi(u),e).value)}catch{return null}};n.left=e(-1),n.right=e(1)}return n}}solveSystem(e,n,t={}){const s=e.map(e=>this.node(e)),i=n??[...new Set(s.flatMap(e=>[...Pe(e)]))].sort(),r=function(e,n,t){const s=[],i=n.map(n=>{const s=Ts(n)?me([ze(n.args[0]),Oe(ze(n.args[1]))]):ze(n),i=t.map(n=>{const t=ls(s,n);if(!t||Math.max(0,...t.keys())>1)throw new D(`not linear in ${n}`);const i=t.get(1)??ee(V.ZERO);if(!ie(i))throw new D(`the coefficient of ${n} must be a number (it is ${e.format(De(i))})`);return i.q});let r=s;for(let e=0;e<t.length;e++)r=me([r,ve([ee(i[e].neg()),ze(k(t[e]))])]);for(const e of t)if(cs(r,e))throw new D(`not linear in ${e}`);return{coeffs:i,rhs:Oe(r)}}),r=()=>i.map(e=>As(De(me(e.coeffs.map((e,n)=>ve([ee(e),ze(k(t[n]))])))),De(e.rhs))).reduce((e,n)=>e?N("&",[e,n]):n,null),o=e=>ei[e]??`${e+1}th`,a=(n,t,i,o)=>{const a=r();a.s!==i.s&&s.push(e.step(n,t,["eliminate"],i,a,o))};let u=0;const l=[];for(let e=0;e<t.length&&u<i.length;e++){const n=i.findIndex((n,t)=>t>=u&&!n.coeffs[e].isZero);if(n<0)continue;const s=k(t[e]);if(n!==u){const e=r();[i[u],i[n]]=[i[n],i[u]],a("system.swap","Swap",e,{v:s,row:o(u),other:o(n)})}const c=i[u],f=c.coeffs[e];if(!f.equals(V.ONE)){const e=r();c.coeffs=c.coeffs.map(e=>e.div(f)),c.rhs=ve([ee(f.inv()),c.rhs]),a("system.scale","Divide",e,{v:s,row:o(u),by:De(ee(f))})}for(let n=0;n<i.length;n++){if(n===u||i[n].coeffs[e].isZero)continue;const t=r(),l=i[n].coeffs[e];i[n].coeffs=i[n].coeffs.map((e,n)=>e.sub(l.mul(c.coeffs[n]))),i[n].rhs=me([i[n].rhs,ve([ee(l.neg()),c.rhs])]);const f=l.sign<0?l.neg():l,p=f.equals(V.ONE);a(`system.${l.sign<0?"add":"subtract"}${p?"":"-multiple"}`,"Eliminate",t,{v:s,row:o(n),from:o(u),k:De(ee(f))})}l.push(e),u++}for(const e of i.slice(u))if(!ie(e.rhs)||!e.rhs.q.isZero)return{solution:null,steps:s,status:"none"};if(l.length<t.length)return{solution:null,steps:s,status:"many"};const c=new Map;return l.forEach((e,n)=>c.set(t[e],De(i[n].rhs))),{solution:c,steps:s,status:"one"}}(this,s,i),o=r.solution?Object.fromEntries([...r.solution].map(([e,n])=>[e,n])):null,a="one"===r.status?i.map(e=>`${e} = ${this.format(o[e])}`).join(", "):"none"===r.status?"no solution":"infinitely many solutions";return{solution:o,status:r.status,text:a,steps:this.select(r.steps,t.steps)}}substitute(e,n,t={}){const s=this.node(e);let i=s;for(const[e,t]of Object.entries(n))i=Bs(i,e,"number"==typeof t?this.node(String(t)):this.node(t));const r=this.simplify(i,t),o=[this.step("substitute","Substitute",["substitute"],s,i)];return{...r,steps:[...this.select(o,t.steps),...r.steps]}}defined(e){const n=this.set.view("define");return n.size?zt(e,n,{format:this.format}).node:e}approximate(e,n={}){const t=this.defined(this.node(e));if(Pe(t).size&&!n.scope){const e=xt(Ze(t),n);return{result:e,text:this.format(e),number:null,exact:!1}}const s=bt(t,n);return{result:s.node,text:s.text,number:s.number,re:s.re,im:s.im,exact:s.exact}}equivalent(e,n){const t=this.node(e),s=this.node(n),i=this.defined(N("-",[t,s])),r=this.simplify(i,{steps:!1}).result;if("num"===r.type&&"0"===r.token)return{equal:!0,how:"exact"};const o=[...Pe(i)];if(!o.length)try{return{equal:Math.abs(bt(i,{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(o.map((n,t)=>[n,String(a[(e+t)%a.length]+t/7)]));let t;try{t=bt(i,{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 xr(e={}){const n=!1===e.defaults?[]:[...hr,...e.complex?dr:[]],{specs:t,messages:s}=function(e){Ot();const n=[],t={};for(const s of e){const e="string"==typeof s?qn(s):s,i=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");d(n.symbol)||f({symbol:String(n.symbol),arity:"any"===n.arity?u:Number(n.arity),label:n.label})}Object.assign(t,(Array.isArray(e)?null:e?.messages)??{});for(const e of i)n.push(e)}return{specs:n,messages:t}}([...n,...e.rules??[]]),i=Y(e.complex,()=>It(t)),r={...br};for(const e of Object.keys(s))for(const n of Object.keys(r))n.startsWith(`${e}.`)&&!(n in s)&&delete r[n];return new yr(i,{...r,...s},e.format??ar,e.read??null,Boolean(e.complex))}const qr=Symbol.for("inlinemath.expressions"),kr=new Map,$r={re:"Re",im:"Im",conj:"overline"},Sr=["Re","Im","re","im","conj","arg"];function Mr(e){const t=[],s=e=>{"op"===e.type?(e.args.forEach(s),n(e.op)?(-1===n(e.op).arity&&t.push(String(e.args.length)),t.push(e.op)):t.push(String(e.args.length),`\\:${$r[e.op]??e.op}`)):t.push(e.token)};return s(e),t}function Nr(n,i){if(!i)return n;const r=new Map;for(const[n,t]of Object.entries(i))if("number"==typeof t?Number.isFinite(t):"bigint"==typeof t||"string"==typeof t)try{r.set(n,e(String(t)))}catch{}if(!r.size)return n;const o=function(e){let n;try{n=t(e)}catch{return new Set}const i=e=>"symbol"===e?.type?e.value:"op"===e?.type&&["=","→"].includes(e.op)&&"symbol"===e.args[0].type?e.args[0].value:null,r=new Set;return s(n,e=>{if("op"!==e.type||e.args.length<2)return;const n=e.op.startsWith("\\:")?e.op.slice(2):e.op;["der","int","lim","diff","derivative","differentiate","integrate","integral","solve","limit"].includes(n)&&i(e.args[1])&&r.add(i(e.args[1]))}),r}(n);return n.flatMap(e=>r.has(e)&&!o.has(e)?r.get(e):[e])}const Or={right:"right",r:"right","+":"right",left:"left",l:"left","-":"left"},Ir=new Set(["simplify","expand","factor","cancel","diff","integrate","solve","approx","limit"]),Ar={integral:"integrate",differentiate:"diff",approximate:"approx",simp:"simplify"};function Er(n={}){const t=n.rules||n.names?null:n.complex?"complex":"default";if(t&&kr.has(t))return kr.get(t);const s=[...n.names??[],...n.complex?Sr:[],...Ir,...Object.keys(Ar)],i=xr({...n,read:n=>e(n,{names:s}),format:ar});return t&&kr.set(t,i),i}function Tr(e={}){const n=e.cas??Er(),t=void 0===e.steps?{}:{steps:e.steps},s=(e,o)=>{let a;try{a=n.read(e)}catch{return i(e,o)}const u=o&&o[qr];u&&(a=a.flatMap(e=>Object.hasOwn(u,e)?u[e]:[e])),a=Nr(a,o);const l=a[a.length-1],c=l?.startsWith("\\:")?Ar[l.slice(2)]??l.slice(2):null,f=c&&Ir.has(c),p="der"===l||"int"===l||"lim"===l;if(!f&&!p)return i(e,o);const h=n.node(a),d=p&&h.op!==l,m=f?h.args:[h],g=e=>e?e.s:void 0,v=(e,s,i)=>{if(!s||"="!==s.op)return n.diff(e,g(s),{...t,order:i});const r=s.args[0].s,o=n.diff(e,r,{...t,order:i}),a=n.substitute(o.result,{[r]:s.args[1].s},t);return{...a,steps:[...o.steps??[],...a.steps??[]]}};let b;try{switch(d?"simplify-read":f?c:"der"===l?"derivative":"lim"===l?"lim":"antiderivative"){case"simplify-read":b=n.simplify(h,t);break;case"simplify":b=n.simplify(m[0],t);break;case"expand":b=n.expand(m[0],t);break;case"factor":b=n.factor(m[0],t);break;case"cancel":b=n.cancel(m[0],t);break;case"diff":b=v(m[0],m[1],m[2]?Number(m[2].s):1);break;case"integrate":b=n.integrate(m[0],g(m[1]),{...t,...m[3]?{from:m[2].s,to:m[3].s}:{}});break;case"solve":b=n.solve(m[0],g(m[1]),t);break;case"lim":b=n.limit(h,void 0,void 0,t);break;case"limit":b=(([e,s,i,r])=>{let o=r?Or[r.s.replace(/^\\/,"")]:void 0;if(r&&!o)throw new Error(`a side is right or left, not ${r.s}`);if(s&&"→"===s.op){[s,i]=s.args;const e="^"===i.op?i.args[1].s.replace(/^\\/,""):null;"+"!==e&&"-"!==e||(o=Or[e],i=i.args[0])}return n.limit(e,g(s),i,{...t,...o?{side:o}:{}})})(m);break;case"approx":b=n.approximate(m[0],{...t,digits:m[1]?Number(m[1].s):15});break;case"derivative":b=v(h.args[0],h.args[1],1);break;default:b=n.integrate(h,void 0,t)}}catch(n){return`(${e})`}if(s.last=b,!b.result)return`"${b.text}"`;const w=r(Mr(b.result));return/^-?\d+(\.\d+)?$/.test(w)?w:`(${w})`};return s}const jr=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function zr(e,n={}){return`<ol class="mv-steps">${e.map(e=>{const t=Mr(A(e.from)),s=o(t,{...n,highlight:e.path&&e.path.length?{path:e.path}:void 0}),i=e.to===e.from?"":`<span class="mv-step-arrow" aria-label="becomes">⟶</span>${o(Mr(A(e.to)),n)}`,r=e.explanation?`<p class="mv-step-why">${jr(e.explanation)}</p>`:"";return`<li class="mv-step" data-rule="${jr(e.id)}"><span class="mv-step-name">${jr(e.name)}</span><div class="mv-step-maths">${s}${i}</div>${r}</li>`}).join("")}</ol>`}export{Tr as casBlocks,Er as mathCAS,zr as stepsHTML,Mr as tokensOf};