solve-engine 1.1.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (395) hide show
  1. package/README.md +12 -17
  2. package/dist/{BytecodeBuilder-Bp9xeTmX.d.cts → BytecodeBuilder-DGGeByAP.d.cts} +18 -0
  3. package/dist/{BytecodeBuilder-Bp9xeTmX.d.ts → BytecodeBuilder-DGGeByAP.d.ts} +18 -0
  4. package/dist/{Configuration-C9W8tJv_.d.cts → Configuration-B6W0-T67.d.cts} +17 -4
  5. package/dist/{Configuration-C9W8tJv_.d.ts → Configuration-B6W0-T67.d.ts} +17 -4
  6. package/dist/{EngineError-B61GS1jp.d.cts → EngineError-Ce1lPkjZ.d.cts} +8 -0
  7. package/dist/{EngineError-B61GS1jp.d.ts → EngineError-Ce1lPkjZ.d.ts} +8 -0
  8. package/dist/{Lexer-BOs7euZe.d.cts → Lexer-B4C1qHXu.d.cts} +1 -1
  9. package/dist/{Lexer-CSI_lwbW.d.ts → Lexer-DKMlj7Sy.d.ts} +1 -1
  10. package/dist/{PackageCompatibility-B-7rK1TD.d.cts → PackageCompatibility-Bn5jnBtA.d.cts} +2 -2
  11. package/dist/{PackageCompatibility-Dh59eF-X.d.ts → PackageCompatibility-CIvq2MP5.d.ts} +2 -2
  12. package/dist/{PackageRegistry-_8rDlvxI.d.ts → PackageRegistry-DzeiWcv4.d.ts} +143 -175
  13. package/dist/{PackageRegistry-BHWJP83F.d.cts → PackageRegistry-dpdurBVO.d.cts} +143 -175
  14. package/dist/{Parselet-BBT8riYh.d.ts → Parselet-B-zoPrTa.d.ts} +9 -6
  15. package/dist/{Parselet-BHcgK9S7.d.cts → Parselet-C4Wu055_.d.cts} +9 -6
  16. package/dist/{ScopeManager-CxA24W5n.d.ts → ScopeManager-C2LDOrDx.d.ts} +14 -16
  17. package/dist/{ScopeManager-8vf02dwj.d.cts → ScopeManager-D7uMXbhS.d.cts} +14 -16
  18. package/dist/{Token-B1hdkedD.d.cts → Token-CbP_OutD.d.cts} +9 -0
  19. package/dist/{Token-B1hdkedD.d.ts → Token-CbP_OutD.d.ts} +9 -0
  20. package/dist/{TokenNormalizer-C6VzZgHa.d.ts → TokenNormalizer-DCWdZjGz.d.ts} +1 -1
  21. package/dist/{TokenNormalizer-DRc1Js1V.d.cts → TokenNormalizer-DnlL7_8c.d.cts} +1 -1
  22. package/dist/{VMCheckpoints-MK--EBH2.d.ts → VMCheckpoints-CGyFhivM.d.ts} +3 -3
  23. package/dist/{VMCheckpoints-ELYqITdF.d.cts → VMCheckpoints-I9jg3jWR.d.cts} +3 -3
  24. package/dist/{Value-BUi1RA3S.d.cts → Value-CCi_Eecs.d.cts} +72 -5
  25. package/dist/{Value-BUi1RA3S.d.ts → Value-CCi_Eecs.d.ts} +72 -5
  26. package/dist/{WorkerError-gzmaopj2.d.cts → WorkerError-B4p6PNfx.d.cts} +1 -1
  27. package/dist/{WorkerError-_-RkoQ5P.d.ts → WorkerError-Dhj9BQ_A.d.ts} +1 -1
  28. package/dist/chunk-2JMFUQZH.js +2 -0
  29. package/dist/chunk-2JMFUQZH.js.map +1 -0
  30. package/dist/chunk-2RWAXT6O.js +0 -1
  31. package/dist/chunk-4BZIYU7S.cjs +3 -0
  32. package/dist/chunk-4BZIYU7S.cjs.map +1 -0
  33. package/dist/chunk-4J7XZSZJ.cjs +5 -0
  34. package/dist/chunk-4J7XZSZJ.cjs.map +1 -0
  35. package/dist/chunk-4QVBSG6B.cjs +2 -0
  36. package/dist/chunk-4QVBSG6B.cjs.map +1 -0
  37. package/dist/chunk-5IJD5L3O.cjs +2 -0
  38. package/dist/chunk-5IJD5L3O.cjs.map +1 -0
  39. package/dist/chunk-62LMTO4F.js +2 -0
  40. package/dist/chunk-62LMTO4F.js.map +1 -0
  41. package/dist/chunk-6CY44ZPG.js +2 -0
  42. package/dist/chunk-6CY44ZPG.js.map +1 -0
  43. package/dist/chunk-6G3PMEPA.js +2 -0
  44. package/dist/chunk-6G3PMEPA.js.map +1 -0
  45. package/dist/chunk-6INX773F.cjs +2 -0
  46. package/dist/chunk-6INX773F.cjs.map +1 -0
  47. package/dist/chunk-6KFVG6UY.cjs +2 -0
  48. package/dist/chunk-6KFVG6UY.cjs.map +1 -0
  49. package/dist/chunk-76F3LCIL.js +4 -0
  50. package/dist/chunk-76F3LCIL.js.map +1 -0
  51. package/dist/chunk-7GK3XEZF.js +2 -0
  52. package/dist/chunk-7GK3XEZF.js.map +1 -0
  53. package/dist/chunk-APN442VD.cjs +2 -0
  54. package/dist/chunk-APN442VD.cjs.map +1 -0
  55. package/dist/chunk-AXMQG5TS.cjs +2 -0
  56. package/dist/chunk-AXMQG5TS.cjs.map +1 -0
  57. package/dist/chunk-CIQOK7Q4.cjs +2 -0
  58. package/dist/chunk-CIQOK7Q4.cjs.map +1 -0
  59. package/dist/chunk-E6Z4NQAS.js +2 -0
  60. package/dist/chunk-E6Z4NQAS.js.map +1 -0
  61. package/dist/chunk-EFJCC6FJ.cjs +2 -0
  62. package/dist/chunk-EFJCC6FJ.cjs.map +1 -0
  63. package/dist/chunk-ESUN2THE.cjs +2 -0
  64. package/dist/chunk-ESUN2THE.cjs.map +1 -0
  65. package/dist/chunk-EVAOPEO4.js +2 -0
  66. package/dist/chunk-EVAOPEO4.js.map +1 -0
  67. package/dist/chunk-EYRBENHC.js +3 -0
  68. package/dist/chunk-EYRBENHC.js.map +1 -0
  69. package/dist/chunk-FDE5HWDI.cjs +2 -0
  70. package/dist/chunk-FDE5HWDI.cjs.map +1 -0
  71. package/dist/chunk-FWW3M36J.cjs +2 -0
  72. package/dist/chunk-FWW3M36J.cjs.map +1 -0
  73. package/dist/chunk-GOIQYUWV.js +2 -0
  74. package/dist/chunk-GOIQYUWV.js.map +1 -0
  75. package/dist/chunk-HFKDWQUL.js +2 -0
  76. package/dist/chunk-HFKDWQUL.js.map +1 -0
  77. package/dist/chunk-HLBYHXQD.cjs +3 -0
  78. package/dist/chunk-HLBYHXQD.cjs.map +1 -0
  79. package/dist/chunk-IANAMBJQ.cjs +2 -0
  80. package/dist/chunk-IANAMBJQ.cjs.map +1 -0
  81. package/dist/chunk-IJMNVBIS.js +2 -0
  82. package/dist/chunk-IJMNVBIS.js.map +1 -0
  83. package/dist/chunk-J4LZD4ZY.js +3 -0
  84. package/dist/chunk-J4LZD4ZY.js.map +1 -0
  85. package/dist/chunk-JAK3RAFA.cjs +2 -0
  86. package/dist/chunk-JAK3RAFA.cjs.map +1 -0
  87. package/dist/chunk-JFAJN3C2.cjs +2 -0
  88. package/dist/chunk-JFAJN3C2.cjs.map +1 -0
  89. package/dist/chunk-JPFCXLJV.js +2 -0
  90. package/dist/chunk-JPFCXLJV.js.map +1 -0
  91. package/dist/chunk-JSPKKNPQ.js +3 -0
  92. package/dist/chunk-JSPKKNPQ.js.map +1 -0
  93. package/dist/chunk-L3FPQSGN.js +2 -0
  94. package/dist/chunk-L3FPQSGN.js.map +1 -0
  95. package/dist/chunk-LR4E4A4W.cjs +2 -0
  96. package/dist/chunk-LR4E4A4W.cjs.map +1 -0
  97. package/dist/chunk-MIQBJGGR.js +2 -0
  98. package/dist/chunk-MIQBJGGR.js.map +1 -0
  99. package/dist/chunk-MPB7KUN5.js +3 -0
  100. package/dist/chunk-MPB7KUN5.js.map +1 -0
  101. package/dist/chunk-MSYX32PF.cjs +2 -0
  102. package/dist/chunk-MSYX32PF.cjs.map +1 -0
  103. package/dist/chunk-MVZUTETT.js +2 -0
  104. package/dist/chunk-MVZUTETT.js.map +1 -0
  105. package/dist/chunk-N7N7MPMK.cjs +2 -0
  106. package/dist/chunk-N7N7MPMK.cjs.map +1 -0
  107. package/dist/chunk-NGBBNL4K.cjs +1 -3
  108. package/dist/chunk-P6WPEUAJ.cjs +2 -0
  109. package/dist/chunk-P6WPEUAJ.cjs.map +1 -0
  110. package/dist/chunk-PS272DZJ.cjs +2 -0
  111. package/dist/chunk-PS272DZJ.cjs.map +1 -0
  112. package/dist/chunk-QXQE7X4S.js +2 -0
  113. package/dist/chunk-QXQE7X4S.js.map +1 -0
  114. package/dist/chunk-R2ENWQ76.js +2 -0
  115. package/dist/chunk-R2ENWQ76.js.map +1 -0
  116. package/dist/chunk-R2SZFJTT.cjs +2 -0
  117. package/dist/chunk-R2SZFJTT.cjs.map +1 -0
  118. package/dist/chunk-RAF57WYO.js +2 -0
  119. package/dist/chunk-RAF57WYO.js.map +1 -0
  120. package/dist/chunk-RSF25YSJ.js +2 -0
  121. package/dist/chunk-RSF25YSJ.js.map +1 -0
  122. package/dist/chunk-SOMGSIO4.cjs +3 -0
  123. package/dist/chunk-SOMGSIO4.cjs.map +1 -0
  124. package/dist/chunk-SUXRZWH2.cjs +3 -0
  125. package/dist/chunk-SUXRZWH2.cjs.map +1 -0
  126. package/dist/chunk-SYYE3QAX.cjs +2 -0
  127. package/dist/chunk-SYYE3QAX.cjs.map +1 -0
  128. package/dist/chunk-SZGK6RIP.cjs +2 -0
  129. package/dist/chunk-SZGK6RIP.cjs.map +1 -0
  130. package/dist/chunk-TCZSPH4A.js +2 -0
  131. package/dist/chunk-TCZSPH4A.js.map +1 -0
  132. package/dist/chunk-TLG7VZRX.cjs +2 -0
  133. package/dist/chunk-TLG7VZRX.cjs.map +1 -0
  134. package/dist/chunk-TRBXW6HW.js +2 -0
  135. package/dist/{chunk-AQNHHJMJ.cjs.map → chunk-TRBXW6HW.js.map} +1 -1
  136. package/dist/chunk-TTFO4YDP.cjs +2 -0
  137. package/dist/chunk-TTFO4YDP.cjs.map +1 -0
  138. package/dist/chunk-TWC7K3ZX.js +2 -0
  139. package/dist/chunk-TWC7K3ZX.js.map +1 -0
  140. package/dist/chunk-UDQ57ZRX.cjs +2 -0
  141. package/dist/chunk-UDQ57ZRX.cjs.map +1 -0
  142. package/dist/chunk-UI6IFGBT.js +2 -0
  143. package/dist/chunk-UI6IFGBT.js.map +1 -0
  144. package/dist/chunk-UURM7P3P.cjs +4 -0
  145. package/dist/chunk-UURM7P3P.cjs.map +1 -0
  146. package/dist/chunk-W2JAR233.js +2 -0
  147. package/dist/chunk-W2JAR233.js.map +1 -0
  148. package/dist/chunk-WGZ3FNHI.js +2 -0
  149. package/dist/chunk-WGZ3FNHI.js.map +1 -0
  150. package/dist/chunk-WN5CMP4T.cjs +3 -0
  151. package/dist/chunk-WN5CMP4T.cjs.map +1 -0
  152. package/dist/chunk-XEIDV5JP.js +2 -0
  153. package/dist/chunk-XEIDV5JP.js.map +1 -0
  154. package/dist/chunk-XNIWQHXY.js +2 -0
  155. package/dist/chunk-XNIWQHXY.js.map +1 -0
  156. package/dist/chunk-XR7HEC7B.js +5 -0
  157. package/dist/chunk-XR7HEC7B.js.map +1 -0
  158. package/dist/chunk-Y7O4D3BJ.cjs +2 -0
  159. package/dist/chunk-Y7O4D3BJ.cjs.map +1 -0
  160. package/dist/chunk-YAYBVVG2.js +3 -0
  161. package/dist/chunk-YAYBVVG2.js.map +1 -0
  162. package/dist/chunk-YJ2OPULK.js +2 -0
  163. package/dist/chunk-YJ2OPULK.js.map +1 -0
  164. package/dist/chunk-YVKHEAFT.js +2 -0
  165. package/dist/chunk-YVKHEAFT.js.map +1 -0
  166. package/dist/chunk-ZCNBT44X.cjs +2 -0
  167. package/dist/chunk-ZCNBT44X.cjs.map +1 -0
  168. package/dist/chunk-ZLRJ7TDP.cjs +2 -0
  169. package/dist/chunk-ZLRJ7TDP.cjs.map +1 -0
  170. package/dist/constants.cjs +1 -21
  171. package/dist/constants.d.cts +1 -1
  172. package/dist/constants.d.ts +1 -1
  173. package/dist/constants.js +1 -4
  174. package/dist/engine.cjs +1 -94
  175. package/dist/engine.d.cts +29 -14
  176. package/dist/engine.d.ts +29 -14
  177. package/dist/engine.js +1 -37
  178. package/dist/errors.cjs +1 -105
  179. package/dist/errors.d.cts +3 -3
  180. package/dist/errors.d.ts +3 -3
  181. package/dist/errors.js +1 -4
  182. package/dist/format.cjs +1 -26
  183. package/dist/format.d.cts +2 -2
  184. package/dist/format.d.ts +2 -2
  185. package/dist/format.js +1 -9
  186. package/dist/index.cjs +1 -314
  187. package/dist/index.cjs.map +1 -1
  188. package/dist/index.d.cts +55 -23
  189. package/dist/index.d.ts +55 -23
  190. package/dist/index.js +1 -278
  191. package/dist/index.js.map +1 -1
  192. package/dist/language.cjs +1 -369
  193. package/dist/language.cjs.map +1 -1
  194. package/dist/language.d.cts +12 -13
  195. package/dist/language.d.ts +12 -13
  196. package/dist/language.js +1 -348
  197. package/dist/language.js.map +1 -1
  198. package/dist/lexer.cjs +1 -63
  199. package/dist/lexer.d.cts +3 -3
  200. package/dist/lexer.d.ts +3 -3
  201. package/dist/lexer.js +1 -10
  202. package/dist/normalizer.cjs +1 -39
  203. package/dist/normalizer.d.cts +3 -3
  204. package/dist/normalizer.d.ts +3 -3
  205. package/dist/normalizer.js +1 -10
  206. package/dist/packages.cjs +1 -128
  207. package/dist/packages.d.cts +39 -14
  208. package/dist/packages.d.ts +39 -14
  209. package/dist/packages.js +1 -23
  210. package/dist/parser.cjs +1 -54
  211. package/dist/parser.d.cts +9 -9
  212. package/dist/parser.d.ts +9 -9
  213. package/dist/parser.js +1 -9
  214. package/dist/{pipeline-CtfJtPQc.d.cts → pipeline-72QmQlGx.d.ts} +3 -3
  215. package/dist/{pipeline-DCd5M6Gk.d.ts → pipeline-DCQicwWX.d.cts} +3 -3
  216. package/dist/resolvers.cjs +1 -12
  217. package/dist/resolvers.d.cts +3 -3
  218. package/dist/resolvers.d.ts +3 -3
  219. package/dist/resolvers.js +1 -3
  220. package/dist/services.cjs +1 -20
  221. package/dist/services.js +1 -3
  222. package/dist/testing.cjs +3 -477
  223. package/dist/testing.cjs.map +1 -1
  224. package/dist/testing.d.cts +12 -13
  225. package/dist/testing.d.ts +12 -13
  226. package/dist/testing.js +3 -469
  227. package/dist/testing.js.map +1 -1
  228. package/dist/uom.cjs +1 -55
  229. package/dist/uom.d.cts +3 -3
  230. package/dist/uom.d.ts +3 -3
  231. package/dist/uom.js +1 -10
  232. package/dist/utilities.cjs +1 -36
  233. package/dist/utilities.js +1 -7
  234. package/dist/vm.cjs +1 -295
  235. package/dist/vm.cjs.map +1 -1
  236. package/dist/vm.d.cts +22 -10
  237. package/dist/vm.d.ts +22 -10
  238. package/dist/vm.js +1 -193
  239. package/dist/vm.js.map +1 -1
  240. package/dist/worker.cjs +2 -492
  241. package/dist/worker.cjs.map +1 -1
  242. package/dist/worker.d.cts +19 -20
  243. package/dist/worker.d.ts +19 -20
  244. package/dist/worker.js +2 -483
  245. package/dist/worker.js.map +1 -1
  246. package/package.json +1 -13
  247. package/dist/chunk-267JPOTF.js +0 -406
  248. package/dist/chunk-267JPOTF.js.map +0 -1
  249. package/dist/chunk-2TZKENDH.cjs +0 -448
  250. package/dist/chunk-2TZKENDH.cjs.map +0 -1
  251. package/dist/chunk-3BOK2LDK.js +0 -17
  252. package/dist/chunk-3BOK2LDK.js.map +0 -1
  253. package/dist/chunk-3OWCDIPN.js +0 -215
  254. package/dist/chunk-3OWCDIPN.js.map +0 -1
  255. package/dist/chunk-3VGDNEE3.js +0 -84
  256. package/dist/chunk-3VGDNEE3.js.map +0 -1
  257. package/dist/chunk-4D6NIHE2.js +0 -451
  258. package/dist/chunk-4D6NIHE2.js.map +0 -1
  259. package/dist/chunk-4HQKTMWG.js +0 -7985
  260. package/dist/chunk-4HQKTMWG.js.map +0 -1
  261. package/dist/chunk-536WPM2V.cjs +0 -283
  262. package/dist/chunk-536WPM2V.cjs.map +0 -1
  263. package/dist/chunk-5HRB36DK.js +0 -405
  264. package/dist/chunk-5HRB36DK.js.map +0 -1
  265. package/dist/chunk-5ON7PUAZ.js +0 -12
  266. package/dist/chunk-5ON7PUAZ.js.map +0 -1
  267. package/dist/chunk-7KYSUDQO.js +0 -109
  268. package/dist/chunk-7KYSUDQO.js.map +0 -1
  269. package/dist/chunk-7ZX6B7SY.cjs +0 -3222
  270. package/dist/chunk-7ZX6B7SY.cjs.map +0 -1
  271. package/dist/chunk-ADBA3XBE.cjs +0 -20
  272. package/dist/chunk-ADBA3XBE.cjs.map +0 -1
  273. package/dist/chunk-ALYRJ72W.cjs +0 -434
  274. package/dist/chunk-ALYRJ72W.cjs.map +0 -1
  275. package/dist/chunk-AMOJYLG2.cjs +0 -1692
  276. package/dist/chunk-AMOJYLG2.cjs.map +0 -1
  277. package/dist/chunk-AQNHHJMJ.cjs +0 -261
  278. package/dist/chunk-B4HBEFTB.cjs +0 -375
  279. package/dist/chunk-B4HBEFTB.cjs.map +0 -1
  280. package/dist/chunk-B7LXJ6LC.cjs +0 -36
  281. package/dist/chunk-B7LXJ6LC.cjs.map +0 -1
  282. package/dist/chunk-B7NLZMQ3.cjs +0 -74
  283. package/dist/chunk-B7NLZMQ3.cjs.map +0 -1
  284. package/dist/chunk-BLI4NIQY.js +0 -98
  285. package/dist/chunk-BLI4NIQY.js.map +0 -1
  286. package/dist/chunk-BYJBUL7U.js +0 -499
  287. package/dist/chunk-BYJBUL7U.js.map +0 -1
  288. package/dist/chunk-CCBZZQAE.js +0 -312
  289. package/dist/chunk-CCBZZQAE.js.map +0 -1
  290. package/dist/chunk-CKQMXMHR.cjs +0 -219
  291. package/dist/chunk-CKQMXMHR.cjs.map +0 -1
  292. package/dist/chunk-CUR2WLI4.cjs +0 -507
  293. package/dist/chunk-CUR2WLI4.cjs.map +0 -1
  294. package/dist/chunk-DLEBSLF4.js +0 -336
  295. package/dist/chunk-DLEBSLF4.js.map +0 -1
  296. package/dist/chunk-E23GZEWL.cjs +0 -209
  297. package/dist/chunk-E23GZEWL.cjs.map +0 -1
  298. package/dist/chunk-EJ3ILXX6.cjs +0 -223
  299. package/dist/chunk-EJ3ILXX6.cjs.map +0 -1
  300. package/dist/chunk-ENKKJYD3.js +0 -333
  301. package/dist/chunk-ENKKJYD3.js.map +0 -1
  302. package/dist/chunk-ENRIK36Q.cjs +0 -94
  303. package/dist/chunk-ENRIK36Q.cjs.map +0 -1
  304. package/dist/chunk-ERCOHGXD.js +0 -356
  305. package/dist/chunk-ERCOHGXD.js.map +0 -1
  306. package/dist/chunk-FD5ZZHEU.js +0 -92
  307. package/dist/chunk-FD5ZZHEU.js.map +0 -1
  308. package/dist/chunk-FEAIOR7N.cjs +0 -91
  309. package/dist/chunk-FEAIOR7N.cjs.map +0 -1
  310. package/dist/chunk-GCM5JHMX.js +0 -88
  311. package/dist/chunk-GCM5JHMX.js.map +0 -1
  312. package/dist/chunk-GLA4JXBO.js +0 -204
  313. package/dist/chunk-GLA4JXBO.js.map +0 -1
  314. package/dist/chunk-HIQ5HSZL.cjs +0 -1923
  315. package/dist/chunk-HIQ5HSZL.cjs.map +0 -1
  316. package/dist/chunk-HVRVSI2Z.cjs +0 -829
  317. package/dist/chunk-HVRVSI2Z.cjs.map +0 -1
  318. package/dist/chunk-I4GAWIPW.js +0 -825
  319. package/dist/chunk-I4GAWIPW.js.map +0 -1
  320. package/dist/chunk-J45BCEZ4.cjs +0 -339
  321. package/dist/chunk-J45BCEZ4.cjs.map +0 -1
  322. package/dist/chunk-JG6ZJ2WU.js +0 -1513
  323. package/dist/chunk-JG6ZJ2WU.js.map +0 -1
  324. package/dist/chunk-L2TE7PMO.cjs +0 -14
  325. package/dist/chunk-L2TE7PMO.cjs.map +0 -1
  326. package/dist/chunk-LHZ6VOA7.js +0 -1764
  327. package/dist/chunk-LHZ6VOA7.js.map +0 -1
  328. package/dist/chunk-MN3LHRGV.cjs +0 -8012
  329. package/dist/chunk-MN3LHRGV.cjs.map +0 -1
  330. package/dist/chunk-MVTOCRV2.js +0 -213
  331. package/dist/chunk-MVTOCRV2.js.map +0 -1
  332. package/dist/chunk-N5NNW4VG.cjs +0 -341
  333. package/dist/chunk-N5NNW4VG.cjs.map +0 -1
  334. package/dist/chunk-N7FNVFXW.cjs +0 -32
  335. package/dist/chunk-N7FNVFXW.cjs.map +0 -1
  336. package/dist/chunk-NKW7LKYU.js +0 -3185
  337. package/dist/chunk-NKW7LKYU.js.map +0 -1
  338. package/dist/chunk-NLNDMWZC.js +0 -31
  339. package/dist/chunk-NLNDMWZC.js.map +0 -1
  340. package/dist/chunk-NNQ2TYDF.js +0 -1848
  341. package/dist/chunk-NNQ2TYDF.js.map +0 -1
  342. package/dist/chunk-NNZAEUDW.js +0 -6792
  343. package/dist/chunk-NNZAEUDW.js.map +0 -1
  344. package/dist/chunk-OUHT5Z36.cjs +0 -393
  345. package/dist/chunk-OUHT5Z36.cjs.map +0 -1
  346. package/dist/chunk-QFTDTX6K.cjs +0 -457
  347. package/dist/chunk-QFTDTX6K.cjs.map +0 -1
  348. package/dist/chunk-SBUFNJVE.js +0 -258
  349. package/dist/chunk-SBUFNJVE.js.map +0 -1
  350. package/dist/chunk-SRGQ72IR.cjs +0 -2800
  351. package/dist/chunk-SRGQ72IR.cjs.map +0 -1
  352. package/dist/chunk-SSV46KFA.cjs +0 -112
  353. package/dist/chunk-SSV46KFA.cjs.map +0 -1
  354. package/dist/chunk-T6ZYQJ63.cjs +0 -6807
  355. package/dist/chunk-T6ZYQJ63.cjs.map +0 -1
  356. package/dist/chunk-UKQHXPGW.js +0 -30
  357. package/dist/chunk-UKQHXPGW.js.map +0 -1
  358. package/dist/chunk-UO6BUV6K.js +0 -278
  359. package/dist/chunk-UO6BUV6K.js.map +0 -1
  360. package/dist/chunk-V4XG5QF6.js +0 -1685
  361. package/dist/chunk-V4XG5QF6.js.map +0 -1
  362. package/dist/chunk-VEKIWQ3F.cjs +0 -39
  363. package/dist/chunk-VEKIWQ3F.cjs.map +0 -1
  364. package/dist/chunk-WWQEY7BV.js +0 -67
  365. package/dist/chunk-WWQEY7BV.js.map +0 -1
  366. package/dist/chunk-WXEHD6TT.js +0 -2795
  367. package/dist/chunk-WXEHD6TT.js.map +0 -1
  368. package/dist/chunk-X6K3HUOY.cjs +0 -86
  369. package/dist/chunk-X6K3HUOY.cjs.map +0 -1
  370. package/dist/chunk-XA4CKRML.cjs +0 -316
  371. package/dist/chunk-XA4CKRML.cjs.map +0 -1
  372. package/dist/chunk-XBTEO4OB.js +0 -391
  373. package/dist/chunk-XBTEO4OB.js.map +0 -1
  374. package/dist/chunk-XIYYHA65.cjs +0 -101
  375. package/dist/chunk-XIYYHA65.cjs.map +0 -1
  376. package/dist/chunk-YLJ4XMA6.js +0 -33
  377. package/dist/chunk-YLJ4XMA6.js.map +0 -1
  378. package/dist/chunk-YRIKITGF.cjs +0 -1768
  379. package/dist/chunk-YRIKITGF.cjs.map +0 -1
  380. package/dist/chunk-Z2XP767T.cjs +0 -35
  381. package/dist/chunk-Z2XP767T.cjs.map +0 -1
  382. package/dist/chunk-Z4X2RWOF.js +0 -37
  383. package/dist/chunk-Z4X2RWOF.js.map +0 -1
  384. package/dist/chunk-Z7XGGLI2.js +0 -455
  385. package/dist/chunk-Z7XGGLI2.js.map +0 -1
  386. package/dist/chunk-ZMW6NU2K.cjs +0 -1516
  387. package/dist/chunk-ZMW6NU2K.cjs.map +0 -1
  388. package/dist/chunk-ZVTWQLK4.cjs +0 -459
  389. package/dist/chunk-ZVTWQLK4.cjs.map +0 -1
  390. package/dist/variables.cjs +0 -17
  391. package/dist/variables.cjs.map +0 -1
  392. package/dist/variables.d.cts +0 -87
  393. package/dist/variables.d.ts +0 -87
  394. package/dist/variables.js +0 -4
  395. package/dist/variables.js.map +0 -1
@@ -1,3185 +0,0 @@
1
- import { VariableResolver } from './chunk-GCM5JHMX.js';
2
- import { sharedCurrencyExchange } from './chunk-Z7XGGLI2.js';
3
- import { decimalFromInteger, toPolynomial, polyDegree, polyCoefficients, fromPolynomial, constNode, rationalDiv, rationalNeg, powNode, callNode, decimalCompare, isRationalZero, rationalMul, rationalSub, rationalAdd, rationalToNumber, rationalCompare, simplifySymbolic, sameShape, decimalFromNumberIfExact, decimalMultiply, decimalToNumber, decimalAdd, decimalNegate, cancelSymbolic, complexNode, complex, RATIONAL_ZERO, rationalFromNumber, freeVariables, symbolicToEntry, rowMajorToColumnMajor, expandSymbolic, matrixMultiply, inverse, determinant, transpose, matrixPower, exactIntegerSqrt, surdNode, rational, decimalIsZero, decimalDivide, decimalSubtract, decimalFromLiteral, decimalRound, substitute, varNode, isRationalOne, RATIONAL_ONE, polyUnivariateVar, COMPLEX_I, squareFreePart, coefficientGcd, polynomialDivide, isZeroPolynomial, exactRationalSqrt, symbolicKey, compareMonomials, signedSurdNode, monomialFromKey, monomialToKey, exactIntegerCbrt } from './chunk-NNQ2TYDF.js';
4
- import { faultedOperand, errorValue, numberValueRational, numberValueUncertain, symbolicValue, numberValue, bigIntValue, uomValue, matrixValue, uomValueExact, percentageValue, stringValue, hexValue } from './chunk-267JPOTF.js';
5
- import { getMeasure, convertUnit } from './chunk-MVTOCRV2.js';
6
- import { UNIT_TABLE } from './chunk-V4XG5QF6.js';
7
- import { ErrorFactory } from './chunk-ERCOHGXD.js';
8
-
9
- // src/symbolic/MultivariateFactor.ts
10
- function exactRoot(value, degree) {
11
- const rootOf = degree === 2 ? exactIntegerSqrt : exactIntegerCbrt;
12
- const numerator = rootOf(value.n);
13
- const denominator = rootOf(value.d);
14
- return numerator === null || denominator === null ? null : { n: numerator, d: denominator };
15
- }
16
- function monomialRoot(key, degree) {
17
- const monomial = monomialFromKey(key);
18
- const root = /* @__PURE__ */ new Map();
19
- for (const [name, exponent] of monomial) {
20
- if (exponent % degree !== 0) return null;
21
- root.set(name, exponent / degree);
22
- }
23
- return monomialToKey(root);
24
- }
25
- function monomialMul(a, b) {
26
- const product2 = monomialFromKey(a);
27
- for (const [name, exponent] of monomialFromKey(b)) {
28
- product2.set(name, (product2.get(name) ?? 0) + exponent);
29
- }
30
- return monomialToKey(product2);
31
- }
32
- function monomialDiv(a, b) {
33
- const quotient = monomialFromKey(a);
34
- for (const [name, exponent] of monomialFromKey(b)) {
35
- const remaining = (quotient.get(name) ?? 0) - exponent;
36
- if (remaining <= 0) quotient.delete(name);
37
- else quotient.set(name, remaining);
38
- }
39
- return monomialToKey(quotient);
40
- }
41
- function monomialGcd(a, b) {
42
- const left = monomialFromKey(a);
43
- const shared = /* @__PURE__ */ new Map();
44
- for (const [name, exponent] of monomialFromKey(b)) {
45
- const other = left.get(name);
46
- if (other !== void 0) shared.set(name, Math.min(other, exponent));
47
- }
48
- return monomialToKey(shared);
49
- }
50
- function namesOf(keys) {
51
- const names = /* @__PURE__ */ new Set();
52
- for (const key of keys) for (const name of monomialFromKey(key).keys()) names.add(name);
53
- return [...names].sort();
54
- }
55
- function termsToNode(terms) {
56
- const map = /* @__PURE__ */ new Map();
57
- for (const term of terms) map.set(term.key, term.coefficient);
58
- return fromPolynomial({ terms: map, vars: namesOf(terms.map((term) => term.key)) });
59
- }
60
- function product(factors) {
61
- let result = factors[0];
62
- for (let i = 1; i < factors.length; i++) result = { kind: "mul", left: result, right: factors[i] };
63
- return result;
64
- }
65
- function orderedTerms(p) {
66
- const terms = [...p.terms].map(([key, coefficient]) => ({ key, coefficient }));
67
- return terms.sort((a, b) => compareMonomials(a.key, b.key, p.vars));
68
- }
69
- function factorMultivariate(p) {
70
- if (p.vars.length < 2) return null;
71
- const terms = orderedTerms(p);
72
- if (terms.length === 2) return factorBinomial(terms[0], terms[1]);
73
- if (terms.length === 3) return factorPerfectSquare(terms);
74
- if (terms.length === 4) return factorByGrouping(terms);
75
- return null;
76
- }
77
- function factorBinomial(first, second) {
78
- const firstPositive = first.coefficient.n > 0n;
79
- const secondPositive = second.coefficient.n > 0n;
80
- if (!firstPositive) return null;
81
- const squares = asPowerPair(first, second, 2);
82
- if (squares !== null && !secondPositive) {
83
- return product([
84
- termsToNode([squares.a, negated(squares.b)]),
85
- termsToNode([squares.a, squares.b])
86
- ]);
87
- }
88
- const cubes = asPowerPair(first, second, 3);
89
- if (cubes === null) return null;
90
- const linear = secondPositive ? termsToNode([cubes.a, cubes.b]) : termsToNode([cubes.a, negated(cubes.b)]);
91
- const middle = secondPositive ? negated(multiplyTerms(cubes.a, cubes.b)) : multiplyTerms(cubes.a, cubes.b);
92
- return product([linear, termsToNode([squareOf(cubes.a), middle, squareOf(cubes.b)])]);
93
- }
94
- function asPowerPair(first, second, degree) {
95
- const magnitude2 = second.coefficient.n < 0n ? rationalNeg(second.coefficient) : second.coefficient;
96
- const firstRoot = exactRoot(first.coefficient, degree);
97
- const secondRoot = exactRoot(magnitude2, degree);
98
- if (firstRoot === null || secondRoot === null) return null;
99
- const firstKey = monomialRoot(first.key, degree);
100
- const secondKey = monomialRoot(second.key, degree);
101
- if (firstKey === null || secondKey === null) return null;
102
- return { a: { key: firstKey, coefficient: firstRoot }, b: { key: secondKey, coefficient: secondRoot } };
103
- }
104
- function negated(term) {
105
- return { key: term.key, coefficient: rationalNeg(term.coefficient) };
106
- }
107
- function multiplyTerms(a, b) {
108
- return { key: monomialMul(a.key, b.key), coefficient: rationalMul(a.coefficient, b.coefficient) };
109
- }
110
- function squareOf(term) {
111
- return multiplyTerms(term, term);
112
- }
113
- function factorPerfectSquare(terms) {
114
- const [first, middle, last] = terms;
115
- if (first.coefficient.n < 0n || last.coefficient.n < 0n) return null;
116
- const roots = asPowerPair(first, last, 2);
117
- if (roots === null) return null;
118
- const cross = multiplyTerms(roots.a, roots.b);
119
- if (cross.key !== middle.key) return null;
120
- const twice = rationalMul(cross.coefficient, { n: 2n, d: 1n });
121
- const negative = middle.coefficient.n < 0n;
122
- const magnitude2 = negative ? rationalNeg(middle.coefficient) : middle.coefficient;
123
- if (!isRationalOne(rationalDiv(magnitude2, twice))) return null;
124
- const base = termsToNode([roots.a, negative ? negated(roots.b) : roots.b]);
125
- return { kind: "pow", base, exponent: constNode(2) };
126
- }
127
- function factorByGrouping(terms) {
128
- const pairings = [
129
- [[0, 1], [2, 3]],
130
- [[0, 2], [1, 3]],
131
- [[0, 3], [1, 2]]
132
- ];
133
- for (const pairing of pairings) {
134
- const first = splitPair(terms[pairing[0][0]], terms[pairing[0][1]]);
135
- const second = splitPair(terms[pairing[1][0]], terms[pairing[1][1]]);
136
- if (first === null || second === null) continue;
137
- if (!cofactorsAgree(first.cofactor, second.cofactor)) continue;
138
- return product([
139
- termsToNode([first.common, second.common]),
140
- termsToNode(first.cofactor)
141
- ]);
142
- }
143
- return null;
144
- }
145
- function splitPair(first, second) {
146
- const shared = monomialGcd(first.key, second.key);
147
- const common = { key: shared, coefficient: first.coefficient };
148
- const cofactor = [
149
- { key: monomialDiv(first.key, shared), coefficient: { n: 1n, d: 1n } },
150
- { key: monomialDiv(second.key, shared), coefficient: rationalDiv(second.coefficient, first.coefficient) }
151
- ];
152
- return cofactor[0].key === cofactor[1].key ? null : { common, cofactor };
153
- }
154
- function cofactorsAgree(a, b) {
155
- if (a.length !== b.length) return false;
156
- return a.every((term, index) => term.key === b[index].key && term.coefficient.n === b[index].coefficient.n && term.coefficient.d === b[index].coefficient.d);
157
- }
158
-
159
- // src/symbolic/Factor.ts
160
- var FACTOR_MAX_DEGREE = 12;
161
- var FACTOR_MAX_ROOT_CANDIDATES = 4096;
162
- function gcd(a, b) {
163
- let x = a < 0n ? -a : a;
164
- let y = b < 0n ? -b : b;
165
- while (y !== 0n) {
166
- const remainder = x % y;
167
- x = y;
168
- y = remainder;
169
- }
170
- return x;
171
- }
172
- function lcm(a, b) {
173
- if (a === 0n || b === 0n) return 0n;
174
- return a / gcd(a, b) * b;
175
- }
176
- function divisors(value) {
177
- const magnitude2 = value < 0n ? -value : value;
178
- if (magnitude2 === 0n) return null;
179
- const found = [];
180
- for (let candidate = 1n; candidate * candidate <= magnitude2; candidate++) {
181
- if (magnitude2 % candidate !== 0n) continue;
182
- found.push(candidate);
183
- const paired = magnitude2 / candidate;
184
- if (paired !== candidate) found.push(paired);
185
- if (found.length > FACTOR_MAX_ROOT_CANDIDATES) return null;
186
- }
187
- return found;
188
- }
189
- function evaluateAt(descending, x) {
190
- let total = RATIONAL_ZERO;
191
- for (const coeff of descending) total = rationalAdd(rationalMul(total, x), coeff);
192
- return total;
193
- }
194
- function divideByRoot(descending, root) {
195
- const quotient = [descending[0]];
196
- for (let i = 1; i < descending.length - 1; i++) {
197
- quotient.push(rationalAdd(descending[i], rationalMul(quotient[i - 1], root)));
198
- }
199
- return quotient;
200
- }
201
- function rationalRoots(descending) {
202
- if (descending.length < 2) return [];
203
- let multiplier = 1n;
204
- for (const coeff of descending) multiplier = lcm(multiplier, coeff.d);
205
- const integers = descending.map((coeff) => coeff.n * multiplier / coeff.d);
206
- const leading = integers[0];
207
- const trailing = integers[integers.length - 1];
208
- if (trailing === 0n) return [];
209
- const numeratorDivisors = divisors(trailing);
210
- const denominatorDivisors = divisors(leading);
211
- if (numeratorDivisors === null || denominatorDivisors === null) {
212
- throw ErrorFactory.execution(
213
- "SYMBOLIC_FACTOR_LIMIT_EXCEEDED",
214
- "This polynomial's coefficients have too many divisors to search for rational roots.",
215
- { limit: FACTOR_MAX_ROOT_CANDIDATES }
216
- );
217
- }
218
- if (numeratorDivisors.length * denominatorDivisors.length > FACTOR_MAX_ROOT_CANDIDATES) {
219
- throw ErrorFactory.execution(
220
- "SYMBOLIC_FACTOR_LIMIT_EXCEEDED",
221
- "This polynomial has too many candidate rational roots to test.",
222
- { limit: FACTOR_MAX_ROOT_CANDIDATES }
223
- );
224
- }
225
- const roots = [];
226
- const seen = /* @__PURE__ */ new Set();
227
- for (const p of numeratorDivisors) {
228
- for (const q of denominatorDivisors) {
229
- for (const sign of [1n, -1n]) {
230
- const candidate = { n: sign * p / gcd(p, q), d: q / gcd(p, q) };
231
- const key = `${candidate.n}/${candidate.d}`;
232
- if (seen.has(key)) continue;
233
- seen.add(key);
234
- if (isRationalZero(evaluateAt(descending, candidate))) roots.push(candidate);
235
- }
236
- }
237
- }
238
- return roots;
239
- }
240
- function linearFactorNode(variable, root) {
241
- if (isRationalZero(root)) return varNode(variable);
242
- return root.n > 0n ? { kind: "sub", left: varNode(variable), right: constNode(root) } : { kind: "add", left: varNode(variable), right: constNode(rationalNeg(root)) };
243
- }
244
- function coefficientsToNode(descending, variable) {
245
- const degree = descending.length - 1;
246
- const terms = /* @__PURE__ */ new Map();
247
- descending.forEach((coeff, index) => {
248
- if (isRationalZero(coeff)) return;
249
- const power3 = degree - index;
250
- terms.set(power3 === 0 ? "" : power3 === 1 ? variable : `${variable}^${power3}`, coeff);
251
- });
252
- return fromPolynomial({ terms, vars: terms.size > 0 ? [variable] : [] });
253
- }
254
- function factorUnivariate(descending, variable) {
255
- const factors = [];
256
- let remaining = [...descending];
257
- let roots = rationalRoots(remaining);
258
- while (roots.length > 0 && remaining.length > 2) {
259
- for (const root of roots) {
260
- let multiplicity = 0;
261
- while (remaining.length > 1 && isRationalZero(evaluateAt(remaining, root))) {
262
- remaining = divideByRoot(remaining, root);
263
- multiplicity++;
264
- }
265
- if (multiplicity > 0) factors.push({ base: linearFactorNode(variable, root), power: multiplicity });
266
- }
267
- roots = remaining.length > 2 ? rationalRoots(remaining) : [];
268
- }
269
- const leftoverDegree = remaining.length - 1;
270
- if (leftoverDegree >= 1) {
271
- factors.push({ base: coefficientsToNode(remaining, variable), power: 1 });
272
- return { content: RATIONAL_ONE, factors };
273
- }
274
- return { content: remaining.length === 1 ? remaining[0] : RATIONAL_ONE, factors };
275
- }
276
- function factorizationToNode(factorization) {
277
- const pieces = [];
278
- if (!isRationalOne(factorization.content)) pieces.push(constNode(factorization.content));
279
- for (const factor of factorization.factors) {
280
- pieces.push(factor.power === 1 ? factor.base : powNode(factor.base, constNode({ n: BigInt(factor.power), d: 1n })));
281
- }
282
- if (pieces.length === 0) return constNode(RATIONAL_ONE);
283
- let result = pieces[0];
284
- for (let i = 1; i < pieces.length; i++) result = { kind: "mul", left: result, right: pieces[i] };
285
- return result;
286
- }
287
- function contentOf(p) {
288
- let numeratorGcd = 0n;
289
- let denominatorLcm = 1n;
290
- for (const coeff of p.terms.values()) {
291
- numeratorGcd = gcd(numeratorGcd, coeff.n);
292
- denominatorLcm = lcm(denominatorLcm, coeff.d);
293
- }
294
- if (numeratorGcd === 0n) return RATIONAL_ONE;
295
- return { n: numeratorGcd, d: denominatorLcm };
296
- }
297
- function extractCommonMonomial(p) {
298
- const common = /* @__PURE__ */ new Map();
299
- for (const name of p.vars) {
300
- let lowest = Infinity;
301
- for (const key of p.terms.keys()) {
302
- const exponent = exponentOf(key, name);
303
- if (exponent < lowest) lowest = exponent;
304
- }
305
- if (lowest > 0 && lowest !== Infinity) common.set(name, lowest);
306
- }
307
- if (common.size === 0) return { monomial: common, reduced: p };
308
- const terms = /* @__PURE__ */ new Map();
309
- for (const [key, coeff] of p.terms) {
310
- const exponents = parseKey(key);
311
- for (const [name, shared] of common) exponents.set(name, (exponents.get(name) ?? 0) - shared);
312
- terms.set(buildKey(exponents), coeff);
313
- }
314
- const names = /* @__PURE__ */ new Set();
315
- for (const key of terms.keys()) for (const name of parseKey(key).keys()) names.add(name);
316
- return { monomial: common, reduced: { terms, vars: [...names].sort() } };
317
- }
318
- function exponentOf(key, name) {
319
- return parseKey(key).get(name) ?? 0;
320
- }
321
- function parseKey(key) {
322
- const exponents = /* @__PURE__ */ new Map();
323
- if (key === "") return exponents;
324
- for (const factor of key.split("*")) {
325
- const caret = factor.indexOf("^");
326
- if (caret === -1) exponents.set(factor, 1);
327
- else exponents.set(factor.slice(0, caret), Number(factor.slice(caret + 1)));
328
- }
329
- return exponents;
330
- }
331
- function buildKey(exponents) {
332
- const names = [...exponents.keys()].filter((name) => (exponents.get(name) ?? 0) > 0).sort();
333
- return names.map((name) => exponents.get(name) === 1 ? name : `${name}^${exponents.get(name)}`).join("*");
334
- }
335
- function monomialNode(monomial) {
336
- const names = [...monomial.keys()].sort();
337
- let result = null;
338
- for (const name of names) {
339
- const exponent = monomial.get(name);
340
- const factor = exponent === 1 ? varNode(name) : powNode(varNode(name), constNode({ n: BigInt(exponent), d: 1n }));
341
- result = result === null ? factor : { kind: "mul", left: result, right: factor };
342
- }
343
- return result;
344
- }
345
- function factorSymbolic(node) {
346
- const polynomial = toPolynomial(node);
347
- if (polynomial === null || polynomial.terms.size === 0) return node;
348
- if (polyDegree(polynomial) > FACTOR_MAX_DEGREE) return node;
349
- if (polynomial.vars.length === 0) return node;
350
- const content = contentOf(polynomial);
351
- const primitive = isRationalOne(content) ? polynomial : scaleTerms(polynomial, rationalDiv(RATIONAL_ONE, content));
352
- const { monomial, reduced } = extractCommonMonomial(primitive);
353
- const monomialFactor = monomialNode(monomial);
354
- const variable = polyUnivariateVar(reduced);
355
- if (variable === null) {
356
- const patterned = factorMultivariate(reduced);
357
- if (patterned !== null) return assemble(content, monomialFactor, patterned);
358
- const pieces2 = buildPieces(content, monomialFactor, reduced);
359
- return pieces2 ?? node;
360
- }
361
- const descending = [...polyCoefficients(reduced, variable)].reverse();
362
- const factorization = factorUnivariate(descending, variable);
363
- const combinedContent = rationalMul(content, factorization.content);
364
- const isUnchanged = factorization.factors.length <= 1 && (factorization.factors[0]?.power ?? 1) === 1 && monomialFactor === null && isRationalOne(combinedContent);
365
- if (isUnchanged) return node;
366
- const pieces = [];
367
- if (!isRationalOne(combinedContent)) pieces.push(constNode(combinedContent));
368
- if (monomialFactor !== null) pieces.push(monomialFactor);
369
- pieces.push(factorizationToNode({ content: RATIONAL_ONE, factors: factorization.factors }));
370
- let result = pieces[0];
371
- for (let i = 1; i < pieces.length; i++) result = { kind: "mul", left: result, right: pieces[i] };
372
- return result;
373
- }
374
- function scaleTerms(p, k) {
375
- const terms = /* @__PURE__ */ new Map();
376
- for (const [key, coeff] of p.terms) terms.set(key, rationalMul(coeff, k));
377
- return { terms, vars: p.vars };
378
- }
379
- function assemble(content, monomialFactor, factored) {
380
- const pieces = [];
381
- if (!isRationalOne(content)) pieces.push(constNode(content));
382
- if (monomialFactor !== null) pieces.push(monomialFactor);
383
- pieces.push(factored);
384
- let result = pieces[0];
385
- for (let i = 1; i < pieces.length; i++) result = { kind: "mul", left: result, right: pieces[i] };
386
- return result;
387
- }
388
- function buildPieces(content, monomialFactor, reduced) {
389
- if (monomialFactor === null && isRationalOne(content)) return null;
390
- const pieces = [];
391
- if (!isRationalOne(content)) pieces.push(constNode(content));
392
- if (monomialFactor !== null) pieces.push(monomialFactor);
393
- pieces.push(fromPolynomial(reduced));
394
- let result = pieces[0];
395
- for (let i = 1; i < pieces.length; i++) result = { kind: "mul", left: result, right: pieces[i] };
396
- return result;
397
- }
398
-
399
- // src/symbolic/CubicQuartic.ts
400
- var TWO = { n: 2n, d: 1n };
401
- var THREE = { n: 3n, d: 1n };
402
- var FOUR = { n: 4n, d: 1n };
403
- function depressCubic(a, b, c, d) {
404
- const shift = rationalNeg(rationalDiv(b, rationalMul(THREE, a)));
405
- const p = rationalDiv(
406
- rationalSub(rationalMul(THREE, rationalMul(a, c)), rationalMul(b, b)),
407
- rationalMul(THREE, rationalMul(a, a))
408
- );
409
- const twoBCubed = rationalMul(TWO, rationalMul(b, rationalMul(b, b)));
410
- const nineABC = rationalMul({ n: 9n, d: 1n }, rationalMul(a, rationalMul(b, c)));
411
- const twentySevenAAD = rationalMul({ n: 27n, d: 1n }, rationalMul(rationalMul(a, a), d));
412
- const q = rationalDiv(
413
- rationalAdd(rationalSub(twoBCubed, nineABC), twentySevenAAD),
414
- rationalMul({ n: 27n, d: 1n }, rationalMul(a, rationalMul(a, a)))
415
- );
416
- return { p, q, shift };
417
- }
418
- function solveCubic(a, b, c, d) {
419
- const { p, q, shift } = depressCubic(a, b, c, d);
420
- const discriminant = rationalNeg(
421
- rationalAdd(
422
- rationalMul(FOUR, rationalMul(p, rationalMul(p, p))),
423
- rationalMul({ n: 27n, d: 1n }, rationalMul(q, q))
424
- )
425
- );
426
- if (rationalCompare(discriminant, RATIONAL_ZERO) > 0) {
427
- return { exact: [], approximate: trigonometricRoots(p, q, shift) };
428
- }
429
- if (isRationalZero(discriminant)) return { exact: repeatedCubicRoots(p, q, shift), approximate: [] };
430
- return { exact: cardanoRoots(p, q, shift), approximate: [] };
431
- }
432
- function repeatedCubicRoots(p, q, shift) {
433
- if (isRationalZero(p)) return [constNode(shift)];
434
- const simple = rationalAdd(rationalDiv(rationalMul(THREE, q), p), shift);
435
- const repeated = rationalAdd(rationalNeg(rationalDiv(rationalMul(THREE, q), rationalMul(TWO, p))), shift);
436
- const ordered = [simple, repeated].sort(rationalCompare);
437
- return ordered.map(constNode);
438
- }
439
- function cardanoRoots(p, q, shift) {
440
- const half = rationalNeg(rationalDiv(q, TWO));
441
- const radicand = rationalAdd(
442
- rationalMul(rationalDiv(q, TWO), rationalDiv(q, TWO)),
443
- rationalMul(rationalDiv(p, THREE), rationalMul(rationalDiv(p, THREE), rationalDiv(p, THREE)))
444
- );
445
- const inner = surdNode(radicand);
446
- const u = { kind: "call", name: "cbrt", args: [{ kind: "add", left: constNode(half), right: inner }] };
447
- const v = { kind: "call", name: "cbrt", args: [{ kind: "sub", left: constNode(half), right: inner }] };
448
- const sum = { kind: "add", left: u, right: v };
449
- const difference = { kind: "sub", left: u, right: v };
450
- const real = { kind: "add", left: constNode(shift), right: { kind: "div", left: { kind: "neg", operand: sum }, right: constNode(TWO) } };
451
- const imaginary = {
452
- kind: "mul",
453
- left: { kind: "div", left: { kind: "mul", left: difference, right: surdNode(THREE) }, right: constNode(TWO) },
454
- right: complexNode(COMPLEX_I)
455
- };
456
- return [
457
- { kind: "add", left: constNode(shift), right: sum },
458
- { kind: "sub", left: real, right: imaginary },
459
- { kind: "add", left: real, right: imaginary }
460
- ];
461
- }
462
- function trigonometricRoots(p, q, shift) {
463
- const pNumber = rationalToNumber(p);
464
- const qNumber = rationalToNumber(q);
465
- const shiftNumber = rationalToNumber(shift);
466
- const magnitude2 = 2 * Math.sqrt(-pNumber / 3);
467
- const ratio = 3 * qNumber / (2 * pNumber) * Math.sqrt(-3 / pNumber);
468
- const angle = Math.acos(Math.min(1, Math.max(-1, ratio))) / 3;
469
- return [0, 1, 2].map((k) => magnitude2 * Math.cos(angle - 2 * Math.PI * k / 3) + shiftNumber).sort((left, right) => left - right);
470
- }
471
- function depressQuartic(b, c, d, e) {
472
- const shift = rationalNeg(rationalDiv(b, FOUR));
473
- const bb = rationalMul(b, b);
474
- const p = rationalSub(c, rationalDiv(rationalMul(THREE, bb), { n: 8n, d: 1n }));
475
- const q = rationalAdd(
476
- rationalSub(d, rationalDiv(rationalMul(b, c), TWO)),
477
- rationalDiv(rationalMul(bb, b), { n: 8n, d: 1n })
478
- );
479
- const r = rationalSub(
480
- rationalAdd(
481
- rationalSub(e, rationalDiv(rationalMul(b, d), FOUR)),
482
- rationalDiv(rationalMul(bb, c), { n: 16n, d: 1n })
483
- ),
484
- rationalDiv(rationalMul(THREE, rationalMul(bb, bb)), { n: 256n, d: 1n })
485
- );
486
- return { p, q, r, shift };
487
- }
488
- function solveQuartic(a, b, c, d, e, solveQuadratic2) {
489
- const monic = (value) => rationalDiv(value, a);
490
- const { p, q, r, shift } = depressQuartic(monic(b), monic(c), monic(d), monic(e));
491
- const roots = isRationalZero(q) ? biquadraticRoots(p, r) : splitQuarticRoots(p, q, r, solveQuadratic2);
492
- if (roots === null) return null;
493
- const shifted = isRationalZero(shift) ? roots : roots.map((root) => ({ kind: "add", left: constNode(shift), right: root }));
494
- return { exact: distinct(shifted), approximate: [] };
495
- }
496
- function distinct(roots) {
497
- const seen = /* @__PURE__ */ new Set();
498
- const unique = [];
499
- for (const root of roots) {
500
- const key = symbolicKey(simplifySymbolic(root));
501
- if (seen.has(key)) continue;
502
- seen.add(key);
503
- unique.push(root);
504
- }
505
- return unique;
506
- }
507
- function biquadraticRoots(p, r) {
508
- const discriminant = rationalSub(rationalMul(p, p), rationalMul(FOUR, r));
509
- if (rationalCompare(discriminant, RATIONAL_ZERO) < 0) return complexBiquadraticRoots(p, r);
510
- const root = exactRationalSqrt(discriminant);
511
- if (root !== null) return rationalSquareRoots(rationalNeg(p), root, isRationalZero(discriminant));
512
- return nestedSquareRoots(p, r, discriminant);
513
- }
514
- function rationalSquareRoots(negatedP, root, repeated) {
515
- const values = repeated ? [rationalDiv(negatedP, TWO)] : [rationalDiv(rationalAdd(negatedP, root), TWO), rationalDiv(rationalSub(negatedP, root), TWO)];
516
- const roots = [];
517
- for (const value of values) {
518
- if (isRationalZero(value)) {
519
- roots.push(constNode(RATIONAL_ZERO));
520
- continue;
521
- }
522
- const square = signedSurdNode(value);
523
- roots.push({ kind: "neg", operand: square }, square);
524
- }
525
- return roots;
526
- }
527
- function nestedSquareRoots(p, r, discriminant) {
528
- const negatedP = constNode(rationalNeg(p));
529
- const surd = surdNode(discriminant);
530
- const negativeP = rationalCompare(p, RATIONAL_ZERO) <= 0;
531
- const solutions = [
532
- { node: halved({ kind: "add", left: negatedP, right: surd }), positive: negativeP || rationalCompare(r, RATIONAL_ZERO) <= 0 },
533
- { node: halved({ kind: "sub", left: negatedP, right: surd }), positive: negativeP && rationalCompare(r, RATIONAL_ZERO) >= 0 }
534
- ];
535
- const roots = [];
536
- for (const { node, positive } of solutions) {
537
- const radicand = positive ? node : { kind: "neg", operand: node };
538
- const magnitude2 = { kind: "call", name: "sqrt", args: [radicand] };
539
- const square = positive ? magnitude2 : { kind: "mul", left: magnitude2, right: complexNode(COMPLEX_I) };
540
- roots.push({ kind: "neg", operand: square }, square);
541
- }
542
- return roots;
543
- }
544
- function halved(node) {
545
- return { kind: "div", left: node, right: constNode(TWO) };
546
- }
547
- function complexBiquadraticRoots(p, r) {
548
- const centre = rationalDiv(rationalNeg(p), TWO);
549
- const modulus = exactRationalSqrt(r);
550
- const re = modulus === null ? nestedSurd(surdNode(r), centre) : surdNode(rationalDiv(rationalAdd(modulus, centre), TWO));
551
- const imaginaryMagnitude = modulus === null ? nestedSurd(surdNode(r), rationalNeg(centre)) : surdNode(rationalDiv(rationalSub(modulus, centre), TWO));
552
- const im = { kind: "mul", left: imaginaryMagnitude, right: complexNode(COMPLEX_I) };
553
- const first = { kind: "add", left: re, right: im };
554
- const second = { kind: "sub", left: re, right: im };
555
- return [
556
- { kind: "neg", operand: first },
557
- { kind: "neg", operand: second },
558
- second,
559
- first
560
- ];
561
- }
562
- function nestedSurd(surd, offset) {
563
- const shifted = offset.n >= 0n ? { kind: "add", left: surd, right: constNode(offset) } : { kind: "sub", left: surd, right: constNode(rationalNeg(offset)) };
564
- return { kind: "call", name: "sqrt", args: [halved(shifted)] };
565
- }
566
- function splitQuarticRoots(p, q, r, solveQuadratic2) {
567
- const resolvent = [
568
- { n: 1n, d: 1n },
569
- rationalMul(TWO, p),
570
- rationalSub(rationalMul(p, p), rationalMul(FOUR, r)),
571
- rationalNeg(rationalMul(q, q))
572
- ];
573
- for (const z of rationalRoots(resolvent)) {
574
- if (rationalCompare(z, RATIONAL_ZERO) <= 0) continue;
575
- const alpha = exactRationalSqrt(z);
576
- if (alpha === null) continue;
577
- const sum = rationalAdd(p, z);
578
- const difference = rationalDiv(q, alpha);
579
- const beta = rationalDiv(rationalSub(sum, difference), TWO);
580
- const gamma = rationalDiv(rationalAdd(sum, difference), TWO);
581
- const one2 = { n: 1n, d: 1n };
582
- return [
583
- ...solveQuadratic2(one2, alpha, beta),
584
- ...solveQuadratic2(one2, rationalNeg(alpha), gamma)
585
- ];
586
- }
587
- return null;
588
- }
589
-
590
- // src/symbolic/NumericRoots.ts
591
- var DURAND_KERNER_MAX_ITERATIONS = 200;
592
- var DURAND_KERNER_TOLERANCE = 1e-14;
593
- var ROOT_RESIDUAL_TOLERANCE = 1e-10;
594
- var ROOT_SEPARATION_TOLERANCE = 1e-10;
595
- var AXIS_SNAP_TOLERANCE = 1e-9;
596
- var CONJUGATE_PAIR_TOLERANCE = 1e-8;
597
- var NEWTON_POLISH_STEPS = 4;
598
- function subtract(a, b) {
599
- return { re: a.re - b.re, im: a.im - b.im };
600
- }
601
- function multiply(a, b) {
602
- return { re: a.re * b.re - a.im * b.im, im: a.re * b.im + a.im * b.re };
603
- }
604
- function divide(a, b) {
605
- if (Math.abs(b.re) >= Math.abs(b.im)) {
606
- const ratio2 = b.im / b.re;
607
- const denominator2 = b.re + b.im * ratio2;
608
- return { re: (a.re + a.im * ratio2) / denominator2, im: (a.im - a.re * ratio2) / denominator2 };
609
- }
610
- const ratio = b.re / b.im;
611
- const denominator = b.re * ratio + b.im;
612
- return { re: (a.re * ratio + a.im) / denominator, im: (a.im * ratio - a.re) / denominator };
613
- }
614
- function magnitude(z) {
615
- return Math.hypot(z.re, z.im);
616
- }
617
- function evaluateAt2(descending, z) {
618
- let re = 0;
619
- let im = 0;
620
- for (const coefficient of descending) {
621
- const nextRe = re * z.re - im * z.im + coefficient;
622
- im = re * z.im + im * z.re;
623
- re = nextRe;
624
- }
625
- return { re, im };
626
- }
627
- function evaluationScale(descending, z) {
628
- const radius = magnitude(z);
629
- let total = 0;
630
- for (const coefficient of descending) total = total * radius + Math.abs(coefficient);
631
- return total;
632
- }
633
- function differentiate(descending) {
634
- const degree = descending.length - 1;
635
- const derivative = [];
636
- for (let i = 0; i < degree; i++) derivative.push(descending[i] * (degree - i));
637
- return derivative;
638
- }
639
- function squareFreeDoubles(descending) {
640
- const ascending = [...descending].reverse();
641
- const squareFree = [...squareFreePart(ascending)].reverse();
642
- const doubles = squareFree.map(rationalToNumber);
643
- if (doubles.some((value) => !Number.isFinite(value))) return null;
644
- return doubles;
645
- }
646
- function initialEstimates(monic) {
647
- const degree = monic.length - 1;
648
- let largest = 0;
649
- for (let i = 1; i < monic.length; i++) largest = Math.max(largest, Math.abs(monic[i]));
650
- const radius = 1 + largest;
651
- const centre = -monic[1] / degree;
652
- const estimates = [];
653
- for (let k = 0; k < degree; k++) {
654
- const angle = 2 * Math.PI * k / degree + Math.PI / (2 * degree);
655
- estimates.push({ re: centre + radius * Math.cos(angle), im: radius * Math.sin(angle) });
656
- }
657
- return estimates;
658
- }
659
- function durandKerner(monic) {
660
- const degree = monic.length - 1;
661
- const estimates = initialEstimates(monic);
662
- for (let iteration = 0; iteration < DURAND_KERNER_MAX_ITERATIONS; iteration++) {
663
- let largestStep = 0;
664
- let largestRoot = 1;
665
- for (let i = 0; i < degree; i++) {
666
- let denominator = { re: 1, im: 0 };
667
- for (let j = 0; j < degree; j++) {
668
- if (i !== j) denominator = multiply(denominator, subtract(estimates[i], estimates[j]));
669
- }
670
- if (denominator.re === 0 && denominator.im === 0) {
671
- estimates[i] = { re: estimates[i].re + 1e-6 * (i + 1), im: estimates[i].im + 1e-6 };
672
- continue;
673
- }
674
- const step = divide(evaluateAt2(monic, estimates[i]), denominator);
675
- if (!Number.isFinite(step.re) || !Number.isFinite(step.im)) return null;
676
- estimates[i] = subtract(estimates[i], step);
677
- largestStep = Math.max(largestStep, magnitude(step));
678
- largestRoot = Math.max(largestRoot, magnitude(estimates[i]));
679
- }
680
- if (largestStep <= DURAND_KERNER_TOLERANCE * largestRoot) return estimates;
681
- }
682
- return null;
683
- }
684
- function polish(monic, derivative, start) {
685
- let candidate = start;
686
- for (let step = 0; step < NEWTON_POLISH_STEPS; step++) {
687
- const slope = evaluateAt2(derivative, candidate);
688
- if (slope.re === 0 && slope.im === 0) break;
689
- const next = subtract(candidate, divide(evaluateAt2(monic, candidate), slope));
690
- if (!Number.isFinite(next.re) || !Number.isFinite(next.im)) break;
691
- candidate = next;
692
- }
693
- return candidate;
694
- }
695
- function snapToAxes(monic, derivative, z) {
696
- const scale2 = Math.max(1, magnitude(z));
697
- if (z.im !== 0 && Math.abs(z.im) <= AXIS_SNAP_TOLERANCE * scale2) {
698
- const candidate = polish(monic, derivative, { re: z.re, im: 0 });
699
- if (isRootWithinTolerance(monic, candidate)) return { re: candidate.re, im: 0 };
700
- }
701
- if (z.re !== 0 && Math.abs(z.re) <= AXIS_SNAP_TOLERANCE * scale2) {
702
- const candidate = polish(monic, derivative, { re: 0, im: z.im });
703
- if (isRootWithinTolerance(monic, candidate)) return { re: 0, im: candidate.im };
704
- }
705
- return z;
706
- }
707
- function isRootWithinTolerance(monic, z) {
708
- if (!Number.isFinite(z.re) || !Number.isFinite(z.im)) return false;
709
- return magnitude(evaluateAt2(monic, z)) <= ROOT_RESIDUAL_TOLERANCE * evaluationScale(monic, z);
710
- }
711
- function pairConjugates(roots) {
712
- const result = [...roots];
713
- const paired = result.map((root) => root.im === 0);
714
- for (let i = 0; i < result.length; i++) {
715
- if (paired[i]) continue;
716
- const wanted = { re: result[i].re, im: -result[i].im };
717
- let partner = -1;
718
- let closest = Number.POSITIVE_INFINITY;
719
- for (let j = i + 1; j < result.length; j++) {
720
- if (paired[j]) continue;
721
- const distance = magnitude(subtract(result[j], wanted));
722
- if (distance < closest) {
723
- closest = distance;
724
- partner = j;
725
- }
726
- }
727
- if (partner === -1 || closest > CONJUGATE_PAIR_TOLERANCE * Math.max(1, magnitude(result[i]))) continue;
728
- const re = (result[i].re + result[partner].re) / 2;
729
- const im = (Math.abs(result[i].im) + Math.abs(result[partner].im)) / 2;
730
- const sign = result[i].im < 0 ? -1 : 1;
731
- result[i] = { re, im: sign * im };
732
- result[partner] = { re, im: -sign * im };
733
- paired[i] = true;
734
- paired[partner] = true;
735
- }
736
- return result;
737
- }
738
- function allSeparated(roots) {
739
- for (let i = 0; i < roots.length; i++) {
740
- for (let j = i + 1; j < roots.length; j++) {
741
- const scale2 = Math.max(1, magnitude(roots[i]), magnitude(roots[j]));
742
- if (magnitude(subtract(roots[i], roots[j])) <= ROOT_SEPARATION_TOLERANCE * scale2) return false;
743
- }
744
- }
745
- return true;
746
- }
747
- function approximateRoots(descending) {
748
- const monic = squareFreeDoubles(descending);
749
- if (monic === null) return null;
750
- if (monic.length < 2) return [];
751
- const converged = durandKerner(monic);
752
- if (converged === null) return null;
753
- const derivative = differentiate(monic);
754
- const roots = pairConjugates(converged).map((root) => snapToAxes(monic, derivative, root));
755
- for (const root of roots) {
756
- if (!isRootWithinTolerance(monic, root)) return null;
757
- }
758
- if (!allSeparated(roots)) return null;
759
- return [...roots].sort((a, b) => a.re - b.re || a.im - b.im);
760
- }
761
-
762
- // src/symbolic/Solve.ts
763
- var SOLVE_MAX_DEGREE = 8;
764
- function evaluateRational(descending, x) {
765
- let total = RATIONAL_ZERO;
766
- for (const coeff of descending) total = rationalAdd(rationalMul(total, x), coeff);
767
- return total;
768
- }
769
- function divideByRoot2(descending, root) {
770
- const quotient = [descending[0]];
771
- for (let i = 1; i < descending.length - 1; i++) {
772
- quotient.push(rationalAdd(descending[i], rationalMul(quotient[i - 1], root)));
773
- }
774
- return quotient;
775
- }
776
- function solveQuadratic(a, b, c) {
777
- const discriminant = rationalSub(rationalMul(b, b), rationalMul(rational4(), rationalMul(a, c)));
778
- const twoA = rationalMul(rational2(), a);
779
- if (rationalCompare(discriminant, RATIONAL_ZERO) < 0) {
780
- return complexQuadraticRoots(rationalNeg(b), discriminant, twoA);
781
- }
782
- if (isRationalZero(discriminant)) return [constNode(rationalDiv(rationalNeg(b), twoA))];
783
- const rootN = exactIntegerSqrt(discriminant.n);
784
- const rootD = exactIntegerSqrt(discriminant.d);
785
- if (rootN !== null && rootD !== null) {
786
- const root = { n: rootN, d: rootD };
787
- const plus = rationalDiv(rationalAdd(rationalNeg(b), root), twoA);
788
- const minus = rationalDiv(rationalSub(rationalNeg(b), root), twoA);
789
- return rationalCompare(minus, plus) <= 0 ? [constNode(minus), constNode(plus)] : [constNode(plus), constNode(minus)];
790
- }
791
- const surd = surdNode(discriminant);
792
- const ascending = rationalCompare(twoA, RATIONAL_ZERO) > 0;
793
- const lower = { kind: "div", left: { kind: "sub", left: constNode(rationalNeg(b)), right: surd }, right: constNode(twoA) };
794
- const upper = { kind: "div", left: { kind: "add", left: constNode(rationalNeg(b)), right: surd }, right: constNode(twoA) };
795
- return ascending ? [lower, upper] : [upper, lower];
796
- }
797
- function complexQuadraticRoots(negatedB, discriminant, twoA) {
798
- const magnitude2 = rationalNeg(discriminant);
799
- const rootN = exactIntegerSqrt(magnitude2.n);
800
- const rootD = exactIntegerSqrt(magnitude2.d);
801
- if (rootN !== null && rootD !== null) {
802
- const imaginary2 = rationalDiv({ n: rootN, d: rootD }, twoA);
803
- const real2 = rationalDiv(negatedB, twoA);
804
- return [
805
- complexNode(complex(real2, rationalNeg(imaginary2))),
806
- complexNode(complex(real2, imaginary2))
807
- ];
808
- }
809
- const real = rationalDiv(negatedB, twoA);
810
- const scaledRadicand = rationalDiv(magnitude2, rationalMul(twoA, twoA));
811
- const imaginary = { kind: "mul", left: surdNode(scaledRadicand), right: complexNode(COMPLEX_I) };
812
- if (isRationalZero(real)) {
813
- return [{ kind: "neg", operand: imaginary }, imaginary];
814
- }
815
- return [
816
- { kind: "sub", left: constNode(real), right: imaginary },
817
- { kind: "add", left: constNode(real), right: imaginary }
818
- ];
819
- }
820
- function rational2() {
821
- return { n: 2n, d: 1n };
822
- }
823
- function rational4() {
824
- return { n: 4n, d: 1n };
825
- }
826
- function realApproximation(value) {
827
- return { re: value, im: 0 };
828
- }
829
- function solveForVariable(lhs, rhs, variable) {
830
- const polynomial = toPolynomial({ kind: "sub", left: lhs, right: rhs });
831
- if (polynomial === null) {
832
- return {
833
- kind: "unsupported",
834
- reason: "this is not a polynomial equation (it divides by an unknown, or calls a function of one)"
835
- };
836
- }
837
- const others = polynomial.vars.filter((name) => name !== variable);
838
- const degree = polyDegree(polynomial, variable);
839
- if (others.length > 0) {
840
- if (degree !== 1) {
841
- return {
842
- kind: "unsupported",
843
- reason: `solving for "${variable}" needs the equation to be linear in it when other unknowns (${others.join(", ")}) are present`
844
- };
845
- }
846
- return solveLinearWithOtherUnknowns(polynomial, variable);
847
- }
848
- if (degree === 0) {
849
- return polynomial.terms.size === 0 ? { kind: "identity" } : { kind: "contradiction" };
850
- }
851
- if (degree > SOLVE_MAX_DEGREE) {
852
- return { kind: "unsupported", reason: `degree ${degree} is above the supported maximum of ${SOLVE_MAX_DEGREE}` };
853
- }
854
- const descending = [...polyCoefficients(polynomial, variable)].reverse();
855
- return solveUnivariate(descending);
856
- }
857
- function solveLinearWithOtherUnknowns(polynomial, variable) {
858
- const coefficientTerms = /* @__PURE__ */ new Map();
859
- const constantTerms = /* @__PURE__ */ new Map();
860
- for (const [key, coeff] of polynomial.terms) {
861
- const factors = key.split("*").filter((part) => part.length > 0);
862
- const index = factors.indexOf(variable);
863
- if (index === -1) {
864
- constantTerms.set(key, coeff);
865
- } else {
866
- factors.splice(index, 1);
867
- coefficientTerms.set(factors.join("*"), coeff);
868
- }
869
- }
870
- const namesOf2 = (terms) => {
871
- const names = /* @__PURE__ */ new Set();
872
- for (const key of terms.keys()) {
873
- for (const part of key.split("*")) {
874
- if (part.length > 0) names.add(part.split("^")[0]);
875
- }
876
- }
877
- return [...names].sort();
878
- };
879
- const coefficient = fromPolynomial({ terms: coefficientTerms, vars: namesOf2(coefficientTerms) });
880
- const constant = fromPolynomial({ terms: constantTerms, vars: namesOf2(constantTerms) });
881
- return {
882
- kind: "roots",
883
- exact: [{ kind: "div", left: { kind: "neg", operand: constant }, right: coefficient }],
884
- approximate: []
885
- };
886
- }
887
- function closedFormRoots(descending) {
888
- if (descending.length === 4) {
889
- return solveCubic(descending[0], descending[1], descending[2], descending[3]);
890
- }
891
- if (descending.length === 5) {
892
- return solveQuartic(descending[0], descending[1], descending[2], descending[3], descending[4], solveQuadratic);
893
- }
894
- return null;
895
- }
896
- function extractRationalRoots(descending) {
897
- const roots = [];
898
- let remaining = [...descending];
899
- let powersOfX = 0;
900
- while (remaining.length > 1 && isRationalZero(remaining[remaining.length - 1])) {
901
- remaining = remaining.slice(0, -1);
902
- powersOfX++;
903
- }
904
- if (powersOfX > 0) roots.push(RATIONAL_ZERO);
905
- while (remaining.length > 1) {
906
- const found = rationalRoots(remaining);
907
- if (found.length === 0) break;
908
- for (const root of found) {
909
- let multiplicity = 0;
910
- while (remaining.length > 1 && isRationalZero(evaluateRational(remaining, root))) {
911
- remaining = divideByRoot2(remaining, root);
912
- multiplicity++;
913
- }
914
- if (multiplicity > 0) roots.push(root);
915
- }
916
- }
917
- return { roots: roots.sort(rationalCompare), remaining };
918
- }
919
- function solveUnivariate(descending) {
920
- const { roots, remaining } = extractRationalRoots(descending);
921
- const exact = roots.map(constNode);
922
- const approximate = [];
923
- const leftoverDegree = remaining.length - 1;
924
- const solvedDegree = descending.length - remaining.length;
925
- if (leftoverDegree <= 0) return finish(exact, approximate, solvedDegree, 0, "");
926
- if (leftoverDegree === 1) {
927
- exact.push(constNode(rationalDiv(rationalNeg(remaining[1]), remaining[0])));
928
- return finish(exact, approximate, solvedDegree + 1, 0, "");
929
- }
930
- if (leftoverDegree === 2) {
931
- exact.push(...solveQuadratic(remaining[0], remaining[1], remaining[2]));
932
- return finish(exact, approximate, solvedDegree + 2, 0, "");
933
- }
934
- const closedForm = closedFormRoots(remaining);
935
- if (closedForm !== null) {
936
- exact.push(...closedForm.exact);
937
- approximate.push(...closedForm.approximate.map(realApproximation));
938
- return finish(exact, approximate, solvedDegree + leftoverDegree, 0, "");
939
- }
940
- const numeric = approximateRoots(remaining);
941
- if (numeric !== null) {
942
- approximate.push(...numeric);
943
- return finish(exact, approximate, solvedDegree + leftoverDegree, 0, "");
944
- }
945
- return finish(
946
- exact,
947
- approximate,
948
- solvedDegree,
949
- leftoverDegree,
950
- `a degree-${leftoverDegree} factor of it has no exact solution here and the numerical method did not converge on that factor`
951
- );
952
- }
953
- function finish(exact, approximate, solvedDegree, unsolvedDegree, reason) {
954
- const found = exact.length + approximate.length;
955
- const incoherent = solvedDegree >= 1 && (found < 1 || found > solvedDegree);
956
- if (unsolvedDegree > 0 || incoherent) {
957
- return {
958
- kind: "incomplete",
959
- exact,
960
- approximate,
961
- // A distinct root can stand for several equal ones, so the count found
962
- // is a lower bound on what it covers. The degree left unsolved is not.
963
- missing: incoherent ? Math.max(1, solvedDegree + unsolvedDegree - found) : unsolvedDegree,
964
- reason: incoherent ? `${found} root${found === 1 ? "" : "s"} were produced for a degree-${solvedDegree + unsolvedDegree} equation, which does not add up` : reason
965
- };
966
- }
967
- return { kind: "roots", exact, approximate };
968
- }
969
-
970
- // src/vm/SymbolicOps.ts
971
- var SYMBOLIC_BUILTIN_NAMES = {
972
- 0: "sqrt",
973
- 1: "abs",
974
- 2: "sin",
975
- 3: "cos",
976
- 4: "tan",
977
- 5: "log",
978
- 6: "ceil",
979
- 7: "floor",
980
- 8: "round",
981
- 11: "asin",
982
- 12: "acos",
983
- 13: "atan",
984
- 14: "atan2",
985
- 15: "sinh",
986
- 16: "cosh",
987
- 17: "tanh",
988
- 18: "asinh",
989
- 19: "acosh",
990
- 20: "atanh",
991
- 21: "cbrt",
992
- 23: "expm1",
993
- 24: "exp",
994
- 26: "hypot",
995
- 28: "log10",
996
- 29: "log1p",
997
- 30: "log2",
998
- 33: "sign",
999
- 34: "trunc",
1000
- // Spelled exactly as `builtinNameToIndex` accepts them, all lower case. A
1001
- // `call` node's name is what gets displayed, so a name the parser would not
1002
- // accept back would render an expression the user cannot retype.
1003
- 35: "degtorad",
1004
- 36: "radtodeg",
1005
- 61: "root",
1006
- 62: "fact"
1007
- };
1008
- var POW_BUILTIN_INDEX = 31;
1009
- var SYMBOLIC_NATIVE_BUILTINS = /* @__PURE__ */ new Set([67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79]);
1010
- function valueToSymbolic(v) {
1011
- if (v.type === 9 /* Symbolic */) return v.value;
1012
- if (v.type === 13 /* Error */ || v.type === 12 /* Pending */) return null;
1013
- const numeric = v.toNumber();
1014
- if (!Number.isFinite(numeric)) return null;
1015
- return constNode(rationalFromNumber(numeric));
1016
- }
1017
- function symbolicToValue(node) {
1018
- const simplified = simplifySymbolic(node);
1019
- if (simplified.kind === "const") return numberValue(rationalToNumber(simplified.value));
1020
- return symbolicValue(simplified);
1021
- }
1022
- function unsupported(what) {
1023
- return errorValue(
1024
- "SYMBOLIC_UNSUPPORTED_FUNCTION",
1025
- `"${what}" cannot be applied to an expression that still contains an unknown.`
1026
- );
1027
- }
1028
- function symbolicPow(l, r) {
1029
- const base = valueToSymbolic(l);
1030
- const exponent = valueToSymbolic(r);
1031
- if (base === null || exponent === null) return unsupported("^");
1032
- return symbolicToValue(powNode(base, exponent));
1033
- }
1034
- function symbolicNeg(v) {
1035
- const operand = valueToSymbolic(v);
1036
- if (operand === null) return unsupported("-");
1037
- return symbolicToValue({ kind: "neg", operand });
1038
- }
1039
- function symbolicBuiltin(index, args) {
1040
- const nodes = [];
1041
- for (const arg of args) {
1042
- const faulted = faultedOperand(arg);
1043
- if (faulted) return faulted;
1044
- const node = valueToSymbolic(arg);
1045
- if (node === null) return unsupported(SYMBOLIC_BUILTIN_NAMES[index] ?? `builtin ${index}`);
1046
- nodes.push(node);
1047
- }
1048
- if (index === POW_BUILTIN_INDEX && nodes.length === 2) {
1049
- return symbolicToValue(powNode(nodes[0], nodes[1]));
1050
- }
1051
- const name = SYMBOLIC_BUILTIN_NAMES[index];
1052
- if (name === void 0) return unsupported(`builtin ${index}`);
1053
- return symbolicToValue(callNode(name, nodes));
1054
- }
1055
- function rootToValue(root) {
1056
- const value = symbolicToValue(root);
1057
- if (value.type === 0 /* Number */ && !Number.isInteger(value.toNumber())) return symbolicValue(root);
1058
- return value;
1059
- }
1060
- function approximateRootToValue(root) {
1061
- if (root.im === 0) return numberValue(root.re);
1062
- return symbolicValue(complexNode(complex(rationalFromNumber(root.re), rationalFromNumber(root.im))));
1063
- }
1064
- function solveOutcomeToValue(outcome) {
1065
- switch (outcome.kind) {
1066
- case "identity":
1067
- return stringValue("true for every value");
1068
- case "contradiction":
1069
- return stringValue("no solution");
1070
- case "unsupported":
1071
- return errorValue("SYMBOLIC_SOLVE_UNSUPPORTED", `Cannot solve this equation: ${outcome.reason}.`);
1072
- case "incomplete": {
1073
- const found = outcome.exact.length + outcome.approximate.length;
1074
- return errorValue(
1075
- "SYMBOLIC_SOLVE_INCOMPLETE",
1076
- `Only ${found} of this equation's ${found + outcome.missing} roots could be found: ${outcome.reason}.`
1077
- );
1078
- }
1079
- case "roots": {
1080
- const values = outcome.exact.map(rootToValue);
1081
- for (const approximate of outcome.approximate) values.push(approximateRootToValue(approximate));
1082
- if (values.length === 0) return stringValue("no solution");
1083
- if (values.length === 1) return values[0];
1084
- return matrixValue(1, values.length, values.map((v) => v.type === 9 /* Symbolic */ ? v.value : v.toNumber()));
1085
- }
1086
- }
1087
- }
1088
- function solveEquationValues(lhsValue, rhsValue, variable) {
1089
- const lhs = valueToSymbolic(lhsValue);
1090
- const rhs = valueToSymbolic(rhsValue);
1091
- if (lhs === null || rhs === null) {
1092
- return errorValue("SYMBOLIC_NONFINITE_OPERAND", "An equation side has no exact value to solve with.");
1093
- }
1094
- return solveOutcomeToValue(solveForVariable(lhs, rhs, variable));
1095
- }
1096
-
1097
- // src/vm/VMConversion.ts
1098
- function unifyUom(l, r) {
1099
- if (l.type === 6 /* Uom */ && r.type === 6 /* Uom */) {
1100
- if (l.unit === r.unit) {
1101
- return { lv: l.toNumber(), rv: r.toNumber(), unit: l.unit, sameMeasure: true };
1102
- }
1103
- const lMeasure = getMeasure(l.unit);
1104
- const rMeasure = getMeasure(r.unit);
1105
- const isCurrency = sharedCurrencyExchange.isCurrency(l.unit) && sharedCurrencyExchange.isCurrency(r.unit);
1106
- if (lMeasure && lMeasure === rMeasure) {
1107
- const rvConverted = convertUnit(r.toNumber(), r.unit, l.unit);
1108
- return { lv: l.toNumber(), rv: rvConverted, unit: l.unit, sameMeasure: true };
1109
- }
1110
- if (isCurrency) {
1111
- const rvConverted = sharedCurrencyExchange.convertSync(r.toNumber(), r.unit, l.unit);
1112
- if (rvConverted !== null) {
1113
- return { lv: l.toNumber(), rv: rvConverted, unit: l.unit, sameMeasure: true };
1114
- }
1115
- }
1116
- return { lv: l.toNumber(), rv: r.toNumber(), unit: void 0, sameMeasure: false };
1117
- }
1118
- if (l.type === 6 /* Uom */) {
1119
- return { lv: l.toNumber(), rv: r.toNumber(), unit: l.unit, sameMeasure: true };
1120
- }
1121
- if (r.type === 6 /* Uom */) {
1122
- return { lv: l.toNumber(), rv: r.toNumber(), unit: r.unit, sameMeasure: true };
1123
- }
1124
- return { lv: l.toNumber(), rv: r.toNumber(), unit: void 0, sameMeasure: true };
1125
- }
1126
- var UNIFIED_COMPARISON_TOLERANCE = 1e-12;
1127
- function largestFiniteMagnitude(a, b, c) {
1128
- let scale2 = 0;
1129
- if (Number.isFinite(a) && Math.abs(a) > scale2) scale2 = Math.abs(a);
1130
- if (Number.isFinite(b) && Math.abs(b) > scale2) scale2 = Math.abs(b);
1131
- if (Number.isFinite(c) && Math.abs(c) > scale2) scale2 = Math.abs(c);
1132
- return scale2;
1133
- }
1134
- function compareUom(l, r) {
1135
- const { lv, rv, sameMeasure } = unifyUom(l, r);
1136
- if (!sameMeasure) return { lv, rv, equal: false, sameMeasure: false };
1137
- if (l.type === 6 /* Uom */ && r.type === 6 /* Uom */ && l.unit !== void 0 && l.unit === r.unit && l.exact !== void 0 && r.exact !== void 0 && sharedCurrencyExchange.isCurrency(l.unit)) {
1138
- return { lv, rv, equal: decimalCompare(l.exact, r.exact) === 0, sameMeasure: true };
1139
- }
1140
- if (lv === rv) return { lv, rv, equal: true, sameMeasure: true };
1141
- if (!Number.isFinite(lv) || !Number.isFinite(rv)) return { lv, rv, equal: false, sameMeasure: true };
1142
- const scale2 = largestFiniteMagnitude(lv, rv, r.toNumber());
1143
- return { lv, rv, equal: Math.abs(lv - rv) <= scale2 * UNIFIED_COMPARISON_TOLERANCE, sameMeasure: true };
1144
- }
1145
- var MEASURE_NOUNS = {
1146
- time: "duration",
1147
- luminousIntensity: "luminous intensity"
1148
- };
1149
- var UNCOUNTABLE_MEASURES = /* @__PURE__ */ new Set(["money", "data"]);
1150
- var COMBINE_VERBS = {
1151
- add: "added",
1152
- sub: "subtracted",
1153
- mul: "multiplied",
1154
- div: "divided"
1155
- };
1156
- function describeMeasure(unit) {
1157
- if (sharedCurrencyExchange.isCurrency(unit)) return "money";
1158
- const measure = getMeasure(unit);
1159
- if (measure === void 0) return void 0;
1160
- return MEASURE_NOUNS[measure] ?? measure;
1161
- }
1162
- function withMeasureArticle(noun) {
1163
- if (UNCOUNTABLE_MEASURES.has(noun)) return noun;
1164
- return /^[aeiou]/.test(noun) ? `an ${noun}` : `a ${noun}`;
1165
- }
1166
- function describeMeasureMismatch(lUnit, rUnit, verb) {
1167
- const left = lUnit === void 0 ? void 0 : describeMeasure(lUnit);
1168
- const right = rUnit === void 0 ? void 0 : describeMeasure(rUnit);
1169
- if (left !== void 0 && right !== void 0 && left !== right) {
1170
- return `${left} and ${right} cannot be ${verb}`;
1171
- }
1172
- return void 0;
1173
- }
1174
- function combineVerb(op) {
1175
- return op !== void 0 ? COMBINE_VERBS[op] ?? "combined" : "combined";
1176
- }
1177
- function describeConversionMismatch(fromUnit, toUnit) {
1178
- const from = describeMeasure(fromUnit);
1179
- const to = describeMeasure(toUnit);
1180
- if (from !== void 0 && to !== void 0 && from !== to) {
1181
- return `${withMeasureArticle(from)} cannot be converted to ${withMeasureArticle(to)}`;
1182
- }
1183
- return void 0;
1184
- }
1185
- function incomparableUnitsError(l, r) {
1186
- const lUnit = l.type === 6 /* Uom */ ? l.unit : void 0;
1187
- const rUnit = r.type === 6 /* Uom */ ? r.unit : void 0;
1188
- const named = describeMeasureMismatch(lUnit, rUnit, "compared");
1189
- return errorValue("INCOMPATIBLE_UNITS", named ?? `Cannot compare incompatible units: ${lUnit ?? "?"} and ${rUnit ?? "?"}`);
1190
- }
1191
- function toBigIntOperand(v) {
1192
- if (v.type === 2 /* BigInt */) return v.value;
1193
- const n = v.toNumber();
1194
- if (!Number.isInteger(n)) {
1195
- const shown = Number.isNaN(n) ? "NaN" : String(n);
1196
- throw ErrorFactory.execution(
1197
- "BIGINT_INEXACT_OPERAND",
1198
- `A whole-number (n) value can only be combined with another whole number, and ${shown} is not one`,
1199
- { operand: shown }
1200
- );
1201
- }
1202
- return BigInt(n);
1203
- }
1204
- function bigIntDivisionByZero() {
1205
- return ErrorFactory.execution(
1206
- "BIGINT_DIVISION_BY_ZERO",
1207
- "Division by zero: a whole-number (n) division is exact integer division, which has no answer at zero, unlike 1 / 0 which is Infinity"
1208
- );
1209
- }
1210
- function compareBigIntOperands(l, r) {
1211
- const lb = exactBigInt(l);
1212
- const rb = exactBigInt(r);
1213
- if (lb === null || rb === null) return null;
1214
- if (lb < rb) return -1;
1215
- if (lb > rb) return 1;
1216
- return 0;
1217
- }
1218
- function exactBigInt(v) {
1219
- if (v.type === 2 /* BigInt */) return v.value;
1220
- const n = v.toNumber();
1221
- return Number.isInteger(n) ? BigInt(n) : null;
1222
- }
1223
- function power(base, exponent) {
1224
- if (Number.isFinite(exponent)) return Math.pow(base, exponent);
1225
- if (base === 1) return 1;
1226
- if (base === -1 && !Number.isNaN(exponent)) return 1;
1227
- return Math.pow(base, exponent);
1228
- }
1229
- function operandExactDecimal(v) {
1230
- if (v.exact !== void 0) return v.exact;
1231
- return decimalFromNumberIfExact(v.toNumber());
1232
- }
1233
- function exactMoneyOp(l, r, op) {
1234
- const lMoney = l.type === 6 /* Uom */ && l.unit !== void 0 && l.exact !== void 0 && sharedCurrencyExchange.isCurrency(l.unit);
1235
- const rMoney = r.type === 6 /* Uom */ && r.unit !== void 0 && r.exact !== void 0 && sharedCurrencyExchange.isCurrency(r.unit);
1236
- if (!lMoney && !rMoney) return null;
1237
- let ld;
1238
- let rd;
1239
- let unit;
1240
- if (lMoney && rMoney) {
1241
- if (l.unit !== r.unit || op === "div") return null;
1242
- ld = l.exact;
1243
- rd = r.exact;
1244
- unit = l.unit;
1245
- } else if (lMoney && r.type !== 6 /* Uom */) {
1246
- ld = l.exact;
1247
- unit = l.unit;
1248
- rd = operandExactDecimal(r);
1249
- } else if (rMoney && l.type !== 6 /* Uom */) {
1250
- rd = r.exact;
1251
- unit = r.unit;
1252
- ld = operandExactDecimal(l);
1253
- } else {
1254
- return null;
1255
- }
1256
- if (ld === null || rd === null) return null;
1257
- let result;
1258
- switch (op) {
1259
- case "add":
1260
- result = decimalAdd(ld, rd);
1261
- break;
1262
- case "sub":
1263
- result = decimalSubtract(ld, rd);
1264
- break;
1265
- case "mul":
1266
- result = decimalMultiply(ld, rd);
1267
- break;
1268
- case "div":
1269
- if (decimalIsZero(rd)) return null;
1270
- result = decimalDivide(ld, rd);
1271
- break;
1272
- }
1273
- return uomValueExact(decimalToNumber(result), unit, result);
1274
- }
1275
- function operandRational(v) {
1276
- if (v.rational !== void 0) return v.rational;
1277
- if ((v.type === 0 /* Number */ || v.type === 1 /* Hex */) && typeof v.value === "number" && Number.isInteger(v.value)) {
1278
- return rational(BigInt(v.value));
1279
- }
1280
- return null;
1281
- }
1282
- function exactRationalOp(l, r, op) {
1283
- const lr = operandRational(l);
1284
- if (lr === null) return null;
1285
- const rr = operandRational(r);
1286
- if (rr === null) return null;
1287
- if (op === "div" && isRationalZero(rr)) return null;
1288
- let result;
1289
- try {
1290
- switch (op) {
1291
- case "add":
1292
- result = rationalAdd(lr, rr);
1293
- break;
1294
- case "sub":
1295
- result = rationalSub(lr, rr);
1296
- break;
1297
- case "mul":
1298
- result = rationalMul(lr, rr);
1299
- break;
1300
- case "div":
1301
- result = rationalDiv(lr, rr);
1302
- break;
1303
- }
1304
- } catch {
1305
- return null;
1306
- }
1307
- return numberValueRational(rationalToNumber(result), result);
1308
- }
1309
- function uncertainOp(l, r, op) {
1310
- if (l.type !== 0 /* Number */ || r.type !== 0 /* Number */) return null;
1311
- const a = l.value;
1312
- const b = r.value;
1313
- const sa = l.uncertainty ?? 0;
1314
- const sb = r.uncertainty ?? 0;
1315
- let center;
1316
- let sigma;
1317
- switch (op) {
1318
- case "add":
1319
- center = a + b;
1320
- sigma = Math.hypot(sa, sb);
1321
- break;
1322
- case "sub":
1323
- center = a - b;
1324
- sigma = Math.hypot(sa, sb);
1325
- break;
1326
- case "mul":
1327
- center = a * b;
1328
- sigma = Math.hypot(b * sa, a * sb);
1329
- break;
1330
- case "div":
1331
- center = a / b;
1332
- sigma = Math.hypot(sa / b, a * sb / (b * b));
1333
- break;
1334
- }
1335
- return numberValueUncertain(center, sigma);
1336
- }
1337
- function compareRationalOperands(l, r) {
1338
- const lr = operandRational(l);
1339
- if (lr === null) return null;
1340
- const rr = operandRational(r);
1341
- if (rr === null) return null;
1342
- return rationalCompare(lr, rr);
1343
- }
1344
- function binaryOp(l, r, op, bigOp, symbolicOp) {
1345
- if (l.type === 13 /* Error */) return l;
1346
- if (r.type === 13 /* Error */) return r;
1347
- if (l.type === 12 /* Pending */) return l;
1348
- if (r.type === 12 /* Pending */) return r;
1349
- if (symbolicOp && (l.type === 9 /* Symbolic */ || r.type === 9 /* Symbolic */)) {
1350
- const left = valueToSymbolic(l);
1351
- const right = valueToSymbolic(r);
1352
- if (left === null || right === null) {
1353
- return errorValue(
1354
- "SYMBOLIC_NONFINITE_OPERAND",
1355
- "A symbolic expression cannot combine with a value that has no exact number (NaN or infinity)."
1356
- );
1357
- }
1358
- const node = { kind: symbolicOp, left, right };
1359
- return symbolicValue(simplifySymbolic(node));
1360
- }
1361
- if (l.type === 0 /* Number */ && r.type === 0 /* Number */) {
1362
- return numberValue(op(l.value, r.value));
1363
- }
1364
- if (l.type === 2 /* BigInt */ || r.type === 2 /* BigInt */) {
1365
- const lb = toBigIntOperand(l);
1366
- const rb = toBigIntOperand(r);
1367
- if (bigOp) return bigIntValue(bigOp(lb, rb));
1368
- return bigIntValue(lb + rb);
1369
- }
1370
- if (l.type === 6 /* Uom */ || r.type === 6 /* Uom */) {
1371
- if (symbolicOp) {
1372
- const exactMoney = exactMoneyOp(l, r, symbolicOp);
1373
- if (exactMoney) return exactMoney;
1374
- }
1375
- const { lv, rv, unit, sameMeasure } = unifyUom(l, r);
1376
- if (!sameMeasure) {
1377
- const lUnit = l.type === 6 /* Uom */ ? l.unit : void 0;
1378
- const rUnit = r.type === 6 /* Uom */ ? r.unit : void 0;
1379
- const named = describeMeasureMismatch(lUnit, rUnit, combineVerb(symbolicOp));
1380
- return errorValue("INCOMPATIBLE_UNITS", named ?? `Cannot combine incompatible units: ${lUnit ?? "?"} and ${rUnit ?? "?"}`);
1381
- }
1382
- return uomValue(op(lv, rv), unit);
1383
- }
1384
- if (l.type === 7 /* Matrix */ && r.type === 7 /* Matrix */) {
1385
- const lm = l.value;
1386
- const rm = r.value;
1387
- if (!sameShape(lm, rm)) {
1388
- return errorValue("DIMENSION_MISMATCH", `Cannot combine matrices of different shapes: ${lm.rows}x${lm.cols} and ${rm.rows}x${rm.cols}`);
1389
- }
1390
- const result = new Array(lm.data.length);
1391
- for (let i = 0; i < lm.data.length; i++) result[i] = op(lm.data[i], rm.data[i]);
1392
- return matrixValue(lm.rows, lm.cols, result);
1393
- }
1394
- if (l.type === 7 /* Matrix */) {
1395
- const lm = l.value;
1396
- const scalar = r.toNumber();
1397
- const result = lm.data.map((v) => op(v, scalar));
1398
- return matrixValue(lm.rows, lm.cols, result);
1399
- }
1400
- if (r.type === 7 /* Matrix */) {
1401
- const rm = r.value;
1402
- const scalar = l.toNumber();
1403
- const result = rm.data.map((v) => op(scalar, v));
1404
- return matrixValue(rm.rows, rm.cols, result);
1405
- }
1406
- return numberValue(op(l.toNumber(), r.toNumber()));
1407
- }
1408
-
1409
- // src/vm/OpRegistry.ts
1410
- var MAX_OPCODE = 254;
1411
- var DYNAMIC_OPCODE_START = 200;
1412
- var OpRegistry = class {
1413
- constructor() {
1414
- this.handlers = /* @__PURE__ */ new Map();
1415
- this.nextOpcode = DYNAMIC_OPCODE_START + 1;
1416
- }
1417
- register(registration) {
1418
- this.handlers.set(registration.opcode, registration.handler);
1419
- }
1420
- /**
1421
- * Remove a previously registered opcode handler.
1422
- * Used by package unregistration to reverse shared-registry contributions.
1423
- */
1424
- unregister(opcode) {
1425
- this.handlers.delete(opcode);
1426
- }
1427
- get(opcode) {
1428
- return this.handlers.get(opcode);
1429
- }
1430
- has(opcode) {
1431
- return this.handlers.has(opcode);
1432
- }
1433
- /**
1434
- * Allocate a unique opcode for a plugin's custom bytecode handler.
1435
- *
1436
- * Returns the next available opcode (starting at 201). Each call
1437
- * returns a distinct value. Plugins should call this once during
1438
- * registration and store the result.
1439
- *
1440
- * @throws If the dynamic opcode pool is exhausted.
1441
- * @returns A unique opcode number for the calling plugin.
1442
- */
1443
- allocateOpcode() {
1444
- if (this.nextOpcode > MAX_OPCODE) {
1445
- throw ErrorFactory.config(
1446
- "OPCODE_POOL_EXHAUSTED",
1447
- `OpRegistry: dynamic opcode pool exhausted (max ${MAX_OPCODE - DYNAMIC_OPCODE_START} allocations).`
1448
- );
1449
- }
1450
- return this.nextOpcode++;
1451
- }
1452
- };
1453
- var sharedOpRegistry = new OpRegistry();
1454
-
1455
- // src/vm/MoneyExact.ts
1456
- var ONE_DECIMAL = decimalFromInteger(1);
1457
- function moneyExactMagnitude(operand, unit) {
1458
- if (!sharedCurrencyExchange.isCurrency(unit)) return null;
1459
- return operand.exact ?? decimalFromNumberIfExact(operand.toNumber());
1460
- }
1461
- function decimalFromShortDecimal(n) {
1462
- if (!Number.isFinite(n)) return null;
1463
- if (Number.isInteger(n)) return decimalFromInteger(BigInt(n));
1464
- const s = String(n);
1465
- if (!/^-?\d+\.\d+$/.test(s)) return null;
1466
- return decimalFromLiteral(s);
1467
- }
1468
- function scaleMoneyExact(amount, factor, unit) {
1469
- const base = moneyExactMagnitude(amount, unit);
1470
- const factorDecimal = decimalFromShortDecimal(factor);
1471
- if (base !== null && factorDecimal !== null) {
1472
- const result = decimalMultiply(base, factorDecimal);
1473
- return uomValueExact(decimalToNumber(result), unit, result);
1474
- }
1475
- return uomValue(amount.toNumber() * factor, unit);
1476
- }
1477
- function scaleMoneyByPercent(money, unit, percent, sign) {
1478
- const base = moneyExactMagnitude(money, unit);
1479
- const percentDecimal = decimalFromShortDecimal(percent);
1480
- if (base !== null && percentDecimal !== null) {
1481
- const factor = decimalAdd(ONE_DECIMAL, sign === 1 ? percentDecimal : decimalNegate(percentDecimal));
1482
- const result = decimalMultiply(base, factor);
1483
- return uomValueExact(decimalToNumber(result), unit, result);
1484
- }
1485
- return uomValue(money.toNumber() * (1 + sign * percent), unit);
1486
- }
1487
- function onePlusRateDecimal(rate) {
1488
- const rateDecimal = decimalFromShortDecimal(rate);
1489
- return rateDecimal === null ? null : decimalAdd(ONE_DECIMAL, rateDecimal);
1490
- }
1491
- function removeTaxExact(money, unit, rate) {
1492
- const base = moneyExactMagnitude(money, unit);
1493
- const divisor = onePlusRateDecimal(rate);
1494
- if (base === null || divisor === null || decimalIsZero(divisor)) return null;
1495
- const quotient = decimalDivide(base, divisor);
1496
- return uomValueExact(decimalToNumber(quotient), unit, quotient);
1497
- }
1498
- function taxInExact(money, unit, rate) {
1499
- const base = moneyExactMagnitude(money, unit);
1500
- const divisor = onePlusRateDecimal(rate);
1501
- if (base === null || divisor === null || decimalIsZero(divisor)) return null;
1502
- const tax = decimalSubtract(base, decimalDivide(base, divisor));
1503
- return uomValueExact(decimalToNumber(tax), unit, tax);
1504
- }
1505
-
1506
- // src/symbolic/PartialFractions.ts
1507
- var APART_MAX_DEGREE = 12;
1508
- function multiply2(a, b) {
1509
- if (a.length === 0 || b.length === 0) return [];
1510
- const product2 = new Array(a.length + b.length - 1).fill(RATIONAL_ZERO);
1511
- a.forEach((left, i) => {
1512
- b.forEach((right, j) => {
1513
- product2[i + j] = rationalAdd(product2[i + j], rationalMul(left, right));
1514
- });
1515
- });
1516
- return product2;
1517
- }
1518
- function power2(base, exponent) {
1519
- let result = [RATIONAL_ONE];
1520
- for (let i = 0; i < exponent; i++) result = multiply2(result, base);
1521
- return result;
1522
- }
1523
- function scale(coefficients, factor) {
1524
- return coefficients.map((coefficient) => rationalDiv(coefficient, factor));
1525
- }
1526
- function denominatorFactors(ascending, variable) {
1527
- const factors = [];
1528
- let lowest = 0;
1529
- while (lowest < ascending.length && isRationalZero(ascending[lowest])) lowest++;
1530
- if (lowest > 0) factors.push({ base: [RATIONAL_ZERO, RATIONAL_ONE], power: lowest });
1531
- const remaining = ascending.slice(lowest);
1532
- if (remaining.length > 1) {
1533
- const factorization = factorUnivariate([...remaining].reverse(), variable);
1534
- for (const factor of factorization.factors) {
1535
- const polynomial = toPolynomial(factor.base);
1536
- if (polynomial === null) return null;
1537
- factors.push({ base: [...polyCoefficients(polynomial, variable)], power: factor.power });
1538
- }
1539
- }
1540
- return factors.length > 0 ? factors : null;
1541
- }
1542
- function enumerateUnknowns(factors) {
1543
- const unknowns = [];
1544
- factors.forEach((factor, index) => {
1545
- const factorDegree = factor.base.length - 1;
1546
- for (let p = 1; p <= factor.power; p++) {
1547
- for (let degree = 0; degree < factorDegree; degree++) {
1548
- unknowns.push({ factor: index, power: p, degree });
1549
- }
1550
- }
1551
- });
1552
- return unknowns;
1553
- }
1554
- function unknownColumn(unknown, factors, denominator) {
1555
- const divisor = power2(factors[unknown.factor].base, unknown.power);
1556
- const { quotient, remainder } = polynomialDivide(denominator, divisor);
1557
- if (!isZeroPolynomial(remainder)) return null;
1558
- const shift = new Array(unknown.degree).fill(RATIONAL_ZERO);
1559
- shift.push(RATIONAL_ONE);
1560
- return multiply2(quotient, shift);
1561
- }
1562
- function solveLinearSystem(matrix, target) {
1563
- const size = target.length;
1564
- for (let column = 0; column < size; column++) {
1565
- let pivot = -1;
1566
- for (let row = column; row < size; row++) {
1567
- if (!isRationalZero(matrix[row][column])) {
1568
- pivot = row;
1569
- break;
1570
- }
1571
- }
1572
- if (pivot === -1) return null;
1573
- [matrix[column], matrix[pivot]] = [matrix[pivot], matrix[column]];
1574
- [target[column], target[pivot]] = [target[pivot], target[column]];
1575
- for (let row = 0; row < size; row++) {
1576
- if (row === column || isRationalZero(matrix[row][column])) continue;
1577
- const factor = rationalDiv(matrix[row][column], matrix[column][column]);
1578
- for (let k = column; k < size; k++) {
1579
- matrix[row][k] = rationalSub(matrix[row][k], rationalMul(factor, matrix[column][k]));
1580
- }
1581
- target[row] = rationalSub(target[row], rationalMul(factor, target[column]));
1582
- }
1583
- }
1584
- return target.map((value, index) => rationalDiv(value, matrix[index][index]));
1585
- }
1586
- function partialFractions(numerator, denominator, variable) {
1587
- if (denominator.length < 2 || denominator.length - 1 > APART_MAX_DEGREE) return null;
1588
- const shared = coefficientGcd(numerator, denominator);
1589
- const reducedNumerator = shared.length > 1 ? polynomialDivide(numerator, shared).quotient : [...numerator];
1590
- const reducedDenominator = shared.length > 1 ? polynomialDivide(denominator, shared).quotient : [...denominator];
1591
- if (reducedDenominator.length === 1) {
1592
- return { polynomial: scale(reducedNumerator, reducedDenominator[0]), terms: [] };
1593
- }
1594
- if (reducedDenominator.length === 0) return null;
1595
- const leading = reducedDenominator[reducedDenominator.length - 1];
1596
- const monicDenominator = scale(reducedDenominator, leading);
1597
- const scaledNumerator = scale(reducedNumerator, leading);
1598
- const { quotient, remainder } = polynomialDivide(scaledNumerator, monicDenominator);
1599
- if (isZeroPolynomial(remainder)) return { polynomial: quotient, terms: [] };
1600
- const factors = denominatorFactors(monicDenominator, variable);
1601
- if (factors === null) return null;
1602
- const terms = solveForNumerators(factors, monicDenominator, remainder);
1603
- return terms === null ? null : { polynomial: quotient, terms };
1604
- }
1605
- function solveForNumerators(factors, denominator, remainder) {
1606
- const unknowns = enumerateUnknowns(factors);
1607
- const size = denominator.length - 1;
1608
- if (unknowns.length !== size) return null;
1609
- const columns = [];
1610
- for (const unknown of unknowns) {
1611
- const column = unknownColumn(unknown, factors, denominator);
1612
- if (column === null) return null;
1613
- columns.push(column);
1614
- }
1615
- const matrix = [];
1616
- for (let row = 0; row < size; row++) {
1617
- matrix.push(columns.map((column) => column[row] ?? RATIONAL_ZERO));
1618
- }
1619
- const target = [];
1620
- for (let row = 0; row < size; row++) target.push(remainder[row] ?? RATIONAL_ZERO);
1621
- const solution = solveLinearSystem(matrix, target);
1622
- if (solution === null) return null;
1623
- return groupSolution(unknowns, solution, factors);
1624
- }
1625
- function groupSolution(unknowns, solution, factors) {
1626
- const grouped = /* @__PURE__ */ new Map();
1627
- unknowns.forEach((unknown, index) => {
1628
- const key = `${unknown.factor}:${unknown.power}`;
1629
- const existing = grouped.get(key) ?? [];
1630
- existing[unknown.degree] = solution[index];
1631
- grouped.set(key, existing);
1632
- });
1633
- const terms = [];
1634
- for (const [key, coefficients] of grouped) {
1635
- const [factorIndex, termPower] = key.split(":").map(Number);
1636
- const filled = [...coefficients].map((value) => value ?? RATIONAL_ZERO);
1637
- if (filled.every(isRationalZero)) continue;
1638
- terms.push({ numerator: filled, base: factors[factorIndex].base, power: termPower });
1639
- }
1640
- return terms;
1641
- }
1642
- function coefficientsToNode2(coefficients, variable) {
1643
- const terms = /* @__PURE__ */ new Map();
1644
- coefficients.forEach((coefficient, exponent) => {
1645
- if (isRationalZero(coefficient)) return;
1646
- terms.set(exponent === 0 ? "" : exponent === 1 ? variable : `${variable}^${exponent}`, coefficient);
1647
- });
1648
- if (terms.size === 0) return constNode(RATIONAL_ZERO);
1649
- return fromPolynomial({ terms, vars: coefficients.length > 1 ? [variable] : [] });
1650
- }
1651
- function apartSymbolic(node) {
1652
- const parts = asRationalFunction(node);
1653
- if (parts === null) return node;
1654
- const decomposition = partialFractions(parts.numerator, parts.denominator, parts.variable);
1655
- if (decomposition === null || decomposition.terms.length === 0) return node;
1656
- let result = decomposition.polynomial.length > 0 ? coefficientsToNode2(decomposition.polynomial, parts.variable) : null;
1657
- for (const term of decomposition.terms) {
1658
- const base = coefficientsToNode2(term.base, parts.variable);
1659
- const denominator = term.power === 1 ? base : powNode(base, constNode({ n: BigInt(term.power), d: 1n }));
1660
- const negative = isNegativeNumerator(term.numerator);
1661
- const numerator = negative ? term.numerator.map((coefficient) => rationalNeg(coefficient)) : term.numerator;
1662
- const piece = {
1663
- kind: "div",
1664
- left: coefficientsToNode2(numerator, parts.variable),
1665
- right: denominator
1666
- };
1667
- if (result === null) result = negative ? { kind: "neg", operand: piece } : piece;
1668
- else result = { kind: negative ? "sub" : "add", left: result, right: piece };
1669
- }
1670
- return result === null ? node : simplifySymbolic(result);
1671
- }
1672
- function isNegativeNumerator(coefficients) {
1673
- return coefficients.some((coefficient) => coefficient.n < 0n) && coefficients.every((coefficient) => coefficient.n <= 0n);
1674
- }
1675
- function asRationalFunction(node) {
1676
- if (node.kind !== "div") return null;
1677
- const numerator = toPolynomial(node.left);
1678
- const denominator = toPolynomial(node.right);
1679
- if (numerator === null || denominator === null) return null;
1680
- const variable = polyUnivariateVar(denominator);
1681
- if (variable === null) return null;
1682
- if (numerator.vars.some((name) => name !== variable)) return null;
1683
- return {
1684
- numerator: polyCoefficients(numerator, variable),
1685
- denominator: polyCoefficients(denominator, variable),
1686
- variable
1687
- };
1688
- }
1689
-
1690
- // src/symbolic/Derivative.ts
1691
- var DERIVATIVE_MAX_ORDER = 16;
1692
- function zero() {
1693
- return constNode(RATIONAL_ZERO);
1694
- }
1695
- function one() {
1696
- return constNode(RATIONAL_ONE);
1697
- }
1698
- function functionDerivative(name, argument) {
1699
- switch (name) {
1700
- case "sin":
1701
- return callNode("cos", [argument]);
1702
- case "cos":
1703
- return { kind: "neg", operand: callNode("sin", [argument]) };
1704
- case "tan":
1705
- return { kind: "div", left: one(), right: powNode(callNode("cos", [argument]), constNode(2)) };
1706
- case "exp":
1707
- return callNode("exp", [argument]);
1708
- case "log":
1709
- return { kind: "div", left: one(), right: argument };
1710
- case "sqrt":
1711
- return {
1712
- kind: "div",
1713
- left: one(),
1714
- right: { kind: "mul", left: constNode(2), right: callNode("sqrt", [argument]) }
1715
- };
1716
- case "asin":
1717
- return { kind: "div", left: one(), right: callNode("sqrt", [oneMinusSquare(argument)]) };
1718
- case "acos":
1719
- return { kind: "neg", operand: { kind: "div", left: one(), right: callNode("sqrt", [oneMinusSquare(argument)]) } };
1720
- case "atan":
1721
- return { kind: "div", left: one(), right: onePlusSquare(argument) };
1722
- case "sinh":
1723
- return callNode("cosh", [argument]);
1724
- case "cosh":
1725
- return callNode("sinh", [argument]);
1726
- case "tanh":
1727
- return { kind: "div", left: one(), right: powNode(callNode("cosh", [argument]), constNode(2)) };
1728
- case "abs":
1729
- return callNode("sign", [argument]);
1730
- default:
1731
- return null;
1732
- }
1733
- }
1734
- function oneMinusSquare(argument) {
1735
- return { kind: "sub", left: one(), right: powNode(argument, constNode(2)) };
1736
- }
1737
- function onePlusSquare(argument) {
1738
- return { kind: "add", left: one(), right: powNode(argument, constNode(2)) };
1739
- }
1740
- function differentiate2(node, variable, order = 1) {
1741
- if (order < 0 || !Number.isInteger(order)) {
1742
- throw ErrorFactory.execution("SYMBOLIC_DERIVATIVE_ORDER_LIMIT", "A derivative order must be a whole number, at least zero.");
1743
- }
1744
- if (order > DERIVATIVE_MAX_ORDER) {
1745
- throw ErrorFactory.execution(
1746
- "SYMBOLIC_DERIVATIVE_ORDER_LIMIT",
1747
- `A derivative order above ${DERIVATIVE_MAX_ORDER} is not supported.`,
1748
- { limit: DERIVATIVE_MAX_ORDER }
1749
- );
1750
- }
1751
- let result = simplifySymbolic(node);
1752
- for (let i = 0; i < order; i++) result = simplifySymbolic(derive(result, variable));
1753
- return result;
1754
- }
1755
- function derive(node, variable) {
1756
- switch (node.kind) {
1757
- case "const":
1758
- case "complex":
1759
- return zero();
1760
- case "var":
1761
- return node.name === variable ? one() : zero();
1762
- case "add":
1763
- return { kind: "add", left: derive(node.left, variable), right: derive(node.right, variable) };
1764
- case "sub":
1765
- return { kind: "sub", left: derive(node.left, variable), right: derive(node.right, variable) };
1766
- case "neg":
1767
- return { kind: "neg", operand: derive(node.operand, variable) };
1768
- case "mul":
1769
- return {
1770
- kind: "add",
1771
- left: { kind: "mul", left: derive(node.left, variable), right: node.right },
1772
- right: { kind: "mul", left: node.left, right: derive(node.right, variable) }
1773
- };
1774
- case "div":
1775
- return {
1776
- kind: "div",
1777
- left: {
1778
- kind: "sub",
1779
- left: { kind: "mul", left: derive(node.left, variable), right: node.right },
1780
- right: { kind: "mul", left: node.left, right: derive(node.right, variable) }
1781
- },
1782
- right: powNode(node.right, constNode(2))
1783
- };
1784
- case "pow":
1785
- return derivePow(node, variable);
1786
- case "call": {
1787
- if (node.args.length !== 1) return unevaluated(node, variable);
1788
- const outer = functionDerivative(node.name, node.args[0]);
1789
- if (outer === null) return unevaluated(node, variable);
1790
- return { kind: "mul", left: outer, right: derive(node.args[0], variable) };
1791
- }
1792
- }
1793
- }
1794
- function derivePow(node, variable) {
1795
- if (node.exponent.kind === "const") {
1796
- const reduced = constNode(rationalSub(node.exponent.value, RATIONAL_ONE));
1797
- return {
1798
- kind: "mul",
1799
- left: { kind: "mul", left: node.exponent, right: powNode(node.base, reduced) },
1800
- right: derive(node.base, variable)
1801
- };
1802
- }
1803
- if (node.base.kind === "const" && node.base.value.n > 0n) {
1804
- return {
1805
- kind: "mul",
1806
- left: { kind: "mul", left: node, right: callNode("log", [node.base]) },
1807
- right: derive(node.exponent, variable)
1808
- };
1809
- }
1810
- return unevaluated(node, variable);
1811
- }
1812
- function unevaluated(node, variable) {
1813
- return callNode("der", [node, varNode(variable)]);
1814
- }
1815
-
1816
- // src/symbolic/Integral.ts
1817
- function asLinear(node, variable) {
1818
- const polynomial = toPolynomial(node);
1819
- if (polynomial === null) return null;
1820
- const others = polynomial.vars.filter((name) => name !== variable);
1821
- if (others.length > 0) return null;
1822
- if (polyDegree(polynomial, variable) > 1) return null;
1823
- const ascending = polyCoefficients(polynomial, variable);
1824
- const intercept = ascending[0] ?? { n: 0n, d: 1n };
1825
- const slope = ascending[1] ?? { n: 0n, d: 1n };
1826
- return isRationalZero(slope) ? null : { slope, intercept };
1827
- }
1828
- function integratePolynomial(node, variable) {
1829
- const polynomial = toPolynomial(node);
1830
- if (polynomial === null) return null;
1831
- const others = polynomial.vars.filter((name) => name !== variable);
1832
- if (others.length > 0) {
1833
- return { ok: false, reason: `it involves more than one unknown (${others.join(", ")})` };
1834
- }
1835
- const ascending = polyCoefficients(polynomial, variable);
1836
- let result = constNode(0);
1837
- ascending.forEach((coeff, power3) => {
1838
- if (isRationalZero(coeff)) return;
1839
- const nextPower = power3 + 1;
1840
- const scaled = rationalDiv(coeff, { n: BigInt(nextPower), d: 1n });
1841
- const term = {
1842
- kind: "mul",
1843
- left: constNode(scaled),
1844
- right: nextPower === 1 ? varNode(variable) : powNode(varNode(variable), constNode(nextPower))
1845
- };
1846
- result = { kind: "add", left: result, right: term };
1847
- });
1848
- return { ok: true, value: simplifySymbolic(result) };
1849
- }
1850
- function integrateStandardForm(node, variable) {
1851
- if (node.kind !== "call" || node.args.length !== 1) return null;
1852
- const linear = asLinear(node.args[0], variable);
1853
- if (linear === null) return null;
1854
- const inner = node.args[0];
1855
- const divideBySlope = (value) => simplifySymbolic({ kind: "div", left: value, right: constNode(linear.slope) });
1856
- switch (node.name) {
1857
- case "exp":
1858
- return { ok: true, value: divideBySlope(callNode("exp", [inner])) };
1859
- case "sin":
1860
- return { ok: true, value: divideBySlope({ kind: "neg", operand: callNode("cos", [inner]) }) };
1861
- case "cos":
1862
- return { ok: true, value: divideBySlope(callNode("sin", [inner])) };
1863
- case "log":
1864
- return {
1865
- ok: true,
1866
- value: divideBySlope({
1867
- kind: "sub",
1868
- left: { kind: "mul", left: inner, right: callNode("log", [inner]) },
1869
- right: inner
1870
- })
1871
- };
1872
- default:
1873
- return null;
1874
- }
1875
- }
1876
- function integrateReciprocalForms(node, variable) {
1877
- if (node.kind !== "div") return null;
1878
- if (node.left.kind !== "const" || !isRationalOneNode(node.left.value)) return null;
1879
- const linear = asLinear(node.right, variable);
1880
- if (linear !== null) {
1881
- return {
1882
- ok: true,
1883
- value: simplifySymbolic({
1884
- kind: "div",
1885
- left: callNode("log", [node.right]),
1886
- right: constNode(linear.slope)
1887
- })
1888
- };
1889
- }
1890
- const denominator = toPolynomial(node.right);
1891
- if (denominator !== null && denominator.vars.length === 1 && denominator.vars[0] === variable) {
1892
- const ascending = polyCoefficients(denominator, variable);
1893
- const isOnePlusSquare = ascending.length === 3 && isRationalOneNode(ascending[0]) && isRationalZero(ascending[1]) && isRationalOneNode(ascending[2]);
1894
- if (isOnePlusSquare) return { ok: true, value: callNode("atan", [varNode(variable)]) };
1895
- }
1896
- return null;
1897
- }
1898
- function isRationalOneNode(value) {
1899
- return value.n === 1n && value.d === 1n;
1900
- }
1901
- function integrateRationalFunction(node, variable) {
1902
- const parts = asRationalFunction(node);
1903
- if (parts === null || parts.variable !== variable) return null;
1904
- const decomposition = partialFractions(parts.numerator, parts.denominator, variable);
1905
- if (decomposition === null) return null;
1906
- let result = decomposition.polynomial.length > 0 ? polynomialAntiderivative(decomposition.polynomial, variable) : constNode(0);
1907
- for (const term of decomposition.terms) {
1908
- const piece = integrateTerm(term, variable);
1909
- if (piece === null) {
1910
- return {
1911
- ok: false,
1912
- reason: "its denominator has a repeated irreducible quadratic factor, which needs a reduction formula this does not have"
1913
- };
1914
- }
1915
- result = { kind: "add", left: result, right: piece };
1916
- }
1917
- return { ok: true, value: simplifySymbolic(result) };
1918
- }
1919
- function integrateTerm(term, variable) {
1920
- const baseDegree = term.base.length - 1;
1921
- const base = coefficientsToNode2(term.base, variable);
1922
- if (baseDegree === 1) {
1923
- const coefficient = term.numerator[0] ?? RATIONAL_ZERO;
1924
- if (term.power === 1) {
1925
- return { kind: "mul", left: constNode(coefficient), right: callNode("log", [base]) };
1926
- }
1927
- const reduced = term.power - 1;
1928
- const scaled = rationalDiv(coefficient, { n: BigInt(-reduced), d: 1n });
1929
- return {
1930
- kind: "div",
1931
- left: constNode(scaled),
1932
- right: powNode(base, constNode({ n: BigInt(reduced), d: 1n }))
1933
- };
1934
- }
1935
- if (baseDegree !== 2 || term.power !== 1) return null;
1936
- return integrateQuadraticTerm(term, variable, base);
1937
- }
1938
- function integrateQuadraticTerm(term, variable, base) {
1939
- const constant = term.numerator[0] ?? RATIONAL_ZERO;
1940
- const linear = term.numerator[1] ?? RATIONAL_ZERO;
1941
- const [q, p] = term.base;
1942
- const half = { n: 1n, d: 2n };
1943
- const halfP = rationalMul(p, half);
1944
- const logarithm = {
1945
- kind: "mul",
1946
- left: constNode(rationalMul(linear, half)),
1947
- right: callNode("log", [base])
1948
- };
1949
- const leftover = rationalSub(constant, rationalMul(linear, halfP));
1950
- if (isRationalZero(leftover)) return logarithm;
1951
- const width = surdNode(rationalSub(q, rationalMul(halfP, halfP)));
1952
- const shifted = {
1953
- kind: "add",
1954
- left: varNode(variable),
1955
- right: constNode(halfP)
1956
- };
1957
- const arctangent = {
1958
- kind: "mul",
1959
- left: { kind: "div", left: constNode(leftover), right: width },
1960
- right: callNode("atan", [{ kind: "div", left: shifted, right: width }])
1961
- };
1962
- return isRationalZero(linear) ? arctangent : { kind: "add", left: logarithm, right: arctangent };
1963
- }
1964
- function polynomialAntiderivative(ascending, variable) {
1965
- let result = constNode(0);
1966
- ascending.forEach((coeff, exponent) => {
1967
- if (isRationalZero(coeff)) return;
1968
- const nextPower = exponent + 1;
1969
- const scaled = rationalDiv(coeff, { n: BigInt(nextPower), d: 1n });
1970
- const term = {
1971
- kind: "mul",
1972
- left: constNode(scaled),
1973
- right: nextPower === 1 ? varNode(variable) : powNode(varNode(variable), constNode(nextPower))
1974
- };
1975
- result = { kind: "add", left: result, right: term };
1976
- });
1977
- return result;
1978
- }
1979
- function integrate(node, variable) {
1980
- const simplified = simplifySymbolic(node);
1981
- if (!freeVariables(simplified).has(variable)) {
1982
- return { ok: true, value: simplifySymbolic({ kind: "mul", left: simplified, right: varNode(variable) }) };
1983
- }
1984
- const polynomial = integratePolynomial(simplified, variable);
1985
- if (polynomial !== null) return polynomial;
1986
- const standard = integrateStandardForm(simplified, variable);
1987
- if (standard !== null) return standard;
1988
- const reciprocal = integrateReciprocalForms(simplified, variable);
1989
- if (reciprocal !== null) return reciprocal;
1990
- const rationalFunction = integrateRationalFunction(simplified, variable);
1991
- if (rationalFunction !== null) return rationalFunction;
1992
- if (simplified.kind === "add" || simplified.kind === "sub") {
1993
- const left = integrate(simplified.left, variable);
1994
- if (!left.ok) return left;
1995
- const right = integrate(simplified.right, variable);
1996
- if (!right.ok) return right;
1997
- return {
1998
- ok: true,
1999
- value: simplifySymbolic({ kind: simplified.kind, left: left.value, right: right.value })
2000
- };
2001
- }
2002
- if (simplified.kind === "mul" && simplified.left.kind === "const") {
2003
- const inner = integrate(simplified.right, variable);
2004
- if (!inner.ok) return inner;
2005
- return { ok: true, value: simplifySymbolic({ kind: "mul", left: simplified.left, right: inner.value }) };
2006
- }
2007
- return {
2008
- ok: false,
2009
- reason: "no elementary antiderivative is known for this expression"
2010
- };
2011
- }
2012
-
2013
- // src/symbolic/Taylor.ts
2014
- var TAYLOR_MAX_DEGREE = 16;
2015
- function taylorSeries(node, variable, point, degree) {
2016
- if (degree < 0 || !Number.isInteger(degree) || degree > TAYLOR_MAX_DEGREE) {
2017
- throw ErrorFactory.execution(
2018
- "SYMBOLIC_TAYLOR_DEGREE_LIMIT",
2019
- `A Taylor degree must be a whole number from 0 to ${TAYLOR_MAX_DEGREE}.`,
2020
- { limit: TAYLOR_MAX_DEGREE }
2021
- );
2022
- }
2023
- const pointNode = constNode(point);
2024
- let factorial = 1n;
2025
- let result = constNode(RATIONAL_ZERO);
2026
- for (let order = 0; order <= degree; order++) {
2027
- if (order > 0) factorial *= BigInt(order);
2028
- const derivative = differentiate2(node, variable, order);
2029
- const atPoint = simplifySymbolic(substitute(derivative, variable, pointNode));
2030
- if (atPoint.kind !== "const") {
2031
- throw ErrorFactory.execution(
2032
- "SYMBOLIC_TAYLOR_INEXACT",
2033
- `The derivative of order ${order} does not reduce to an exact number at the expansion point, so this series cannot be computed exactly.`,
2034
- { order }
2035
- );
2036
- }
2037
- const coefficient = rationalDiv(atPoint.value, { n: factorial, d: 1n });
2038
- if (isRationalZero(coefficient)) continue;
2039
- const shifted = isRationalZero(point) ? varNode(variable) : { kind: "sub", left: varNode(variable), right: pointNode };
2040
- const power3 = order === 0 ? constNode(1) : order === 1 ? shifted : powNode(shifted, constNode(order));
2041
- result = { kind: "add", left: result, right: { kind: "mul", left: constNode(coefficient), right: power3 } };
2042
- }
2043
- return simplifySymbolic(result);
2044
- }
2045
- function jacobian(functions, variables) {
2046
- return functions.map((fn) => variables.map((variable) => differentiate2(fn, variable)));
2047
- }
2048
-
2049
- // src/engine/EngineContext.ts
2050
- function createEngineContext() {
2051
- return {
2052
- pluginFunctions: {},
2053
- opRegistry: new OpRegistry(),
2054
- variableResolver: new VariableResolver(),
2055
- pluginFunctionOwners: {}
2056
- };
2057
- }
2058
- var defaultEngineContext = createEngineContext();
2059
-
2060
- // src/packages/finance/data/CpiTable.ts
2061
- var CPI_TABLE = {
2062
- 1970: 38.8,
2063
- 1971: 40.5,
2064
- 1972: 41.8,
2065
- 1973: 44.4,
2066
- 1974: 49.3,
2067
- 1975: 53.8,
2068
- 1976: 56.9,
2069
- 1977: 60.6,
2070
- 1978: 65.2,
2071
- 1979: 72.6,
2072
- 1980: 82.4,
2073
- 1981: 90.9,
2074
- 1982: 96.5,
2075
- 1983: 99.6,
2076
- 1984: 103.9,
2077
- 1985: 107.6,
2078
- 1986: 109.6,
2079
- 1987: 113.6,
2080
- 1988: 118.3,
2081
- 1989: 124,
2082
- 1990: 130.7,
2083
- 1991: 136.2,
2084
- 1992: 140.3,
2085
- 1993: 144.5,
2086
- 1994: 148.2,
2087
- 1995: 152.4,
2088
- 1996: 156.9,
2089
- 1997: 160.5,
2090
- 1998: 163,
2091
- 1999: 166.6,
2092
- 2e3: 172.2,
2093
- 2001: 177.1,
2094
- 2002: 179.9,
2095
- 2003: 184,
2096
- 2004: 188.9,
2097
- 2005: 195.3,
2098
- 2006: 201.6,
2099
- 2007: 207.3,
2100
- 2008: 215.3,
2101
- 2009: 214.5,
2102
- 2010: 218.1,
2103
- 2011: 224.9,
2104
- 2012: 229.6,
2105
- 2013: 233,
2106
- 2014: 236.7,
2107
- 2015: 237,
2108
- 2016: 240,
2109
- 2017: 245.1,
2110
- 2018: 251.1,
2111
- 2019: 255.7,
2112
- 2020: 258.8,
2113
- 2021: 271,
2114
- 2022: 292.7,
2115
- 2023: 304.7,
2116
- 2024: 313.7,
2117
- // 2025-2026 were projected from model knowledge and are now derived from
2118
- // the IMF monthly CPI series (statisticsoftheworld.com,
2119
- // IMF.CPI.YOY.M?geo=USA), chained forward from the published 2024 figure
2120
- // using annual mean year-over-year rates. 2026 covers January to June only,
2121
- // so it remains a partial year and will move.
2122
- //
2123
- // The projections were 320.6 and 327.4, low by 0.49% and 1.63%. Everything
2124
- // from 2021 to 2024 reproduced the same series to within 0.02%, which is
2125
- // what makes those two the only entries worth changing.
2126
- 2025: 322.2,
2127
- 2026: 332.7
2128
- };
2129
- var CPI_MIN_YEAR = 1970;
2130
- var CPI_MAX_YEAR = 2026;
2131
- function getCpi(year) {
2132
- return CPI_TABLE[Math.trunc(year)];
2133
- }
2134
- function inflationRatio(fromYear, toYear) {
2135
- const fromCpi = getCpi(fromYear);
2136
- const toCpi = getCpi(toYear);
2137
- if (fromCpi === void 0 || toCpi === void 0 || fromCpi === 0) return void 0;
2138
- return toCpi / fromCpi;
2139
- }
2140
- function adjustForInflation(amount, fromYear, toYear) {
2141
- const ratio = inflationRatio(fromYear, toYear);
2142
- if (ratio === void 0) return void 0;
2143
- return amount * ratio;
2144
- }
2145
-
2146
- // src/vm/VMBuiltins.ts
2147
- var ANGLE_KIND = 0;
2148
- function angleInRadians(value) {
2149
- if (value.type === 6 /* Uom */ && value.unit !== void 0) {
2150
- const entry = UNIT_TABLE[value.unit.toLowerCase()];
2151
- if (entry !== void 0 && entry[0] === ANGLE_KIND) return value.toNumber() * entry[1];
2152
- }
2153
- return value.toNumber();
2154
- }
2155
- function pluraliseUnit(unit, count) {
2156
- if (count === 1) return unit;
2157
- const plural = `${unit}s`;
2158
- return UNIT_TABLE[plural.toLowerCase()] === void 0 ? unit : plural;
2159
- }
2160
- function extremum(args, wantLargest) {
2161
- let best;
2162
- let hasNaN = false;
2163
- for (const a of args) {
2164
- if (Number.isNaN(a.toNumber())) {
2165
- hasNaN = true;
2166
- continue;
2167
- }
2168
- if (best === void 0) {
2169
- best = a;
2170
- continue;
2171
- }
2172
- const { lv, rv, sameMeasure } = unifyUom(best, a);
2173
- if (!sameMeasure) {
2174
- const bestUnit = best.type === 6 /* Uom */ ? best.unit : void 0;
2175
- const otherUnit = a.type === 6 /* Uom */ ? a.unit : void 0;
2176
- const named = describeMeasureMismatch(bestUnit, otherUnit, "compared");
2177
- return errorValue(
2178
- "INCOMPATIBLE_UNITS",
2179
- named ?? `Cannot compare incompatible units: ${bestUnit ?? "?"} and ${otherUnit ?? "?"}`
2180
- );
2181
- }
2182
- if (wantLargest ? rv > lv : rv < lv) best = a;
2183
- }
2184
- if (hasNaN) return numberValue(NaN);
2185
- if (best === void 0) return numberValue(wantLargest ? -Infinity : Infinity);
2186
- return best.type === 6 /* Uom */ ? best : numberValue(best.toNumber());
2187
- }
2188
- function keepUnit(operand, magnitude2) {
2189
- if (operand.type === 6 /* Uom */ && operand.unit !== void 0) return uomValue(magnitude2, operand.unit);
2190
- return numberValue(magnitude2);
2191
- }
2192
- function roundToPlaces(source, places) {
2193
- const p = Number.isFinite(places) ? Math.min(100, Math.max(0, Math.trunc(places))) : 0;
2194
- if (source.exact !== void 0) {
2195
- const rounded = decimalRound(source.exact, p);
2196
- return withPlaces(source, decimalToNumber(rounded), p, rounded);
2197
- }
2198
- const value = source.toNumber();
2199
- if (!Number.isFinite(value)) return withPlaces(source, value, p);
2200
- const scale2 = Math.pow(10, p);
2201
- const scaled = value * scale2;
2202
- if (!Number.isFinite(scaled) || Math.abs(scaled) > Number.MAX_SAFE_INTEGER) return withPlaces(source, value, p);
2203
- return withPlaces(source, Math.round(scaled) / scale2, p);
2204
- }
2205
- function withPlaces(source, magnitude2, places, exact) {
2206
- const result = source.type === 6 /* Uom */ && source.unit !== void 0 ? uomValue(magnitude2, source.unit) : numberValue(magnitude2);
2207
- result.decimalPlaces = places;
2208
- if (exact !== void 0) result.exact = exact;
2209
- return result;
2210
- }
2211
- function nonFiniteEuclidOperand(a, b, name) {
2212
- if (Number.isFinite(a) && Number.isFinite(b)) return null;
2213
- const culprit = Number.isFinite(a) ? b : a;
2214
- return errorValue(
2215
- "INVALID_INTEGER_OPERAND",
2216
- `${name} needs two whole numbers, and ${Number.isNaN(culprit) ? "one of them has no value" : "one of them is infinite"}`
2217
- );
2218
- }
2219
- function euclidGcd(a, b) {
2220
- let x = a;
2221
- let y = b;
2222
- while (y !== 0) {
2223
- const t = y;
2224
- y = x % y;
2225
- x = t;
2226
- }
2227
- return x;
2228
- }
2229
- var builtinFunctions = {
2230
- // ── Populated below ──
2231
- // sqrt: a negative argument has a complex answer now that there is a complex
2232
- // number to give, so this no longer quietly returns NaN. The exact path runs
2233
- // first, so sqrt(-4) is 2i rather than an approximation.
2234
- 0: (args) => {
2235
- const value = args[0].toNumber();
2236
- if (value >= 0) return numberValue(Math.sqrt(value));
2237
- return symbolicToValue(callNode("sqrt", [constNode(value)]));
2238
- },
2239
- // abs(a): for a Matrix, "|a|" (Calca's determinant-pipe notation) is a
2240
- // valid alias for det(a) (index 64), reusing the SAME implementation
2241
- // not a separate one. Plain-number abs is unaffected.
2242
- 1: (args) => args[0].type === 7 /* Matrix */ ? determinant(args[0].value) : keepUnit(args[0], Math.abs(args[0].toNumber())),
2243
- // sin/cos/tan accept an angle with a unit; see angleInRadians().
2244
- 2: (args) => numberValue(Math.sin(angleInRadians(args[0]))),
2245
- 3: (args) => numberValue(Math.cos(angleInRadians(args[0]))),
2246
- 4: (args) => numberValue(Math.tan(angleInRadians(args[0]))),
2247
- 5: (args) => numberValue(Math.log(args[0].toNumber())),
2248
- // round/ceil/floor keep a unit for the same reason abs does; see keepUnit().
2249
- 6: (args) => keepUnit(args[0], Math.ceil(args[0].toNumber())),
2250
- 7: (args) => keepUnit(args[0], Math.floor(args[0].toNumber())),
2251
- 8: (args) => args.length >= 2 ? (
2252
- // round(x, n): round to n decimal places and display at that precision.
2253
- roundToPlaces(args[0], args[1].toNumber())
2254
- ) : (
2255
- // round(x): nearest whole number, the way it always was.
2256
- keepUnit(args[0], Math.round(args[0].toNumber()))
2257
- ),
2258
- // min/max: see extremum() for why the winner is carried around as a Value
2259
- // rather than as a running number.
2260
- 9: (args) => extremum(args, false),
2261
- 10: (args) => extremum(args, true),
2262
- 11: (args) => numberValue(Math.asin(args[0].toNumber())),
2263
- 12: (args) => numberValue(Math.acos(args[0].toNumber())),
2264
- 13: (args) => numberValue(Math.atan(args[0].toNumber())),
2265
- 14: (args) => numberValue(Math.atan2(args[0].toNumber(), args[1].toNumber())),
2266
- 15: (args) => numberValue(Math.sinh(args[0].toNumber())),
2267
- 16: (args) => numberValue(Math.cosh(args[0].toNumber())),
2268
- 17: (args) => numberValue(Math.tanh(args[0].toNumber())),
2269
- 18: (args) => numberValue(Math.asinh(args[0].toNumber())),
2270
- 19: (args) => numberValue(Math.acosh(args[0].toNumber())),
2271
- 20: (args) => numberValue(Math.atanh(args[0].toNumber())),
2272
- 21: (args) => numberValue(Math.cbrt(args[0].toNumber())),
2273
- 22: (args) => numberValue(Math.clz32(args[0].toNumber())),
2274
- 23: (args) => numberValue(Math.expm1(args[0].toNumber())),
2275
- 24: (args) => numberValue(Math.exp(args[0].toNumber())),
2276
- 25: (args) => numberValue(Math.fround(args[0].toNumber())),
2277
- // hypot: left as .map()+spread (unlike min/max above), Math.hypot uses
2278
- // a numerically-stable scaling algorithm internally to avoid overflow
2279
- // for very large/small inputs; a naive manual reimplementation risks
2280
- // silently changing results at the extremes, so the tiny array
2281
- // allocation here is the safer trade.
2282
- 26: (args) => numberValue(Math.hypot(...args.map((a) => a.toNumber()))),
2283
- 27: (args) => numberValue(Math.imul(args[0].toNumber(), args[1].toNumber())),
2284
- 28: (args) => numberValue(Math.log10(args[0].toNumber())),
2285
- 29: (args) => numberValue(Math.log1p(args[0].toNumber())),
2286
- 30: (args) => numberValue(Math.log2(args[0].toNumber())),
2287
- // pow(): the spelled-out form of `^`, so a Matrix base means the same
2288
- // repeated matrix multiplication `^` means. Without this branch
2289
- // `pow([1,2;3,4], 2)` was Math.pow of a value whose toNumber() is 0, and
2290
- // came back as the number 0. See vm/MatrixOps.ts's matrixPower().
2291
- 31: (args) => {
2292
- if (args[0].type === 7 /* Matrix */) {
2293
- if (args[1].type !== 0 /* Number */) {
2294
- return errorValue("MATRIX_POWER_UNSUPPORTED", `pow: a matrix's exponent must be a whole number, as in "pow([1,2;3,4], 2)".`);
2295
- }
2296
- return matrixPower(args[0].value, args[1].value);
2297
- }
2298
- if (args[1].type === 7 /* Matrix */) {
2299
- return errorValue("MATRIX_POWER_UNSUPPORTED", `pow: a matrix may only be the base, as in "pow([1,2;3,4], 2)".`);
2300
- }
2301
- return numberValue(power(args[0].toNumber(), args[1].toNumber()));
2302
- },
2303
- 32: () => numberValue(Math.random()),
2304
- // takes no arguments, unlike its neighbours
2305
- 33: (args) => numberValue(Math.sign(args[0].toNumber())),
2306
- 34: (args) => numberValue(Math.trunc(args[0].toNumber())),
2307
- 35: (args) => numberValue(args[0].toNumber() * Math.PI / 180),
2308
- 36: (args) => numberValue(args[0].toNumber() * 180 / Math.PI),
2309
- // 37: diceRoll(from, to), random integer in range [from, to] inclusive.
2310
- // A reversed range (from > to) used to silently produce values outside
2311
- // [to, from] via a negative-length Math.random() spread (e.g.
2312
- // "roll(6, 1)" returning values like 2-5, never 1 or 6) instead of
2313
- // erroring on the invalid input.
2314
- 37: (args) => {
2315
- const from = args[0].toNumber();
2316
- const to = args[1].toNumber();
2317
- if (from > to) {
2318
- return errorValue("INVALID_RANGE", `roll: invalid range, ${from} is greater than ${to}`);
2319
- }
2320
- return numberValue(Math.floor(Math.random() * (to - from + 1)) + from);
2321
- },
2322
- // gcd(a, b), Euclidean algorithm. Negative inputs are treated by
2323
- // magnitude (gcd is conventionally defined over non-negative integers).
2324
- 38: (args) => {
2325
- const a = Math.trunc(Math.abs(args[0].toNumber()));
2326
- const b = Math.trunc(Math.abs(args[1].toNumber()));
2327
- const nonFinite = nonFiniteEuclidOperand(a, b, "gcd");
2328
- if (nonFinite) return nonFinite;
2329
- return numberValue(euclidGcd(a, b));
2330
- },
2331
- // lcm(a, b) = |a*b| / gcd(a, b), via the same Euclidean gcd inline
2332
- // (a standalone gcd() call site, no shared helper needed for two uses).
2333
- 39: (args) => {
2334
- const a = Math.trunc(Math.abs(args[0].toNumber()));
2335
- const b = Math.trunc(Math.abs(args[1].toNumber()));
2336
- const nonFinite = nonFiniteEuclidOperand(a, b, "lcm");
2337
- if (nonFinite) return nonFinite;
2338
- if (a === 0 || b === 0) return numberValue(0);
2339
- return numberValue(a / euclidGcd(a, b) * b);
2340
- },
2341
- // permutation(n, r) = n! / (n-r)!, computed as a running product
2342
- // rather than two full factorials, so it stays exact for n well
2343
- // beyond where n! itself would exceed Number.MAX_SAFE_INTEGER.
2344
- //
2345
- // The loop stops the moment the product stops being a representable
2346
- // double, which is both the answer `fact` (index 62) already gives for
2347
- // the same question and the thing that bounds the loop at all. `r` comes
2348
- // straight off the stack: `permutation(1000000000000, 1000000000000)`
2349
- // used to run a trillion iterations, of which the first ~170 computed
2350
- // something and the rest multiplied Infinity by a number, and it had not
2351
- // returned after thirty seconds. Every factor here is at least 1 and they
2352
- // descend from `n`, so a product that is still finite after 170 steps
2353
- // means the factors are small, which in turn means `r <= n` is small: the
2354
- // early exit bounds the trip count without a separate estimate, and
2355
- // without ever refusing a permutation that does have an answer.
2356
- 40: (args) => {
2357
- const n = Math.trunc(args[0].toNumber());
2358
- const r = Math.trunc(args[1].toNumber());
2359
- if (n < 0 || r < 0 || r > n) {
2360
- return errorValue("INVALID_RANGE", `permutation: invalid n=${n}, r=${r} (require 0 <= r <= n)`);
2361
- }
2362
- let result = 1;
2363
- for (let i = 0; i < r; i++) {
2364
- result *= n - i;
2365
- if (!Number.isFinite(result)) {
2366
- return errorValue(
2367
- "PERMUTATION_OVERFLOW",
2368
- `permutation: P(${n}, ${r}) exceeds the maximum representable double (it passed it after ${i + 1} of ${r} factors)`
2369
- );
2370
- }
2371
- }
2372
- return numberValue(result);
2373
- },
2374
- // combination(n, r) = n! / (r! * (n-r)!), multiply-then-divide one
2375
- // step at a time (standard technique) keeps every intermediate result
2376
- // an integer, avoiding the overflow a naive factorial-ratio would hit.
2377
- //
2378
- // Same early exit, and needed for the same reason: `k = min(r, n-r)`
2379
- // halves the trip count and bounds nothing, so `combination(1e12, 5e11)`
2380
- // asked for five hundred billion iterations. The running value is C(n, i),
2381
- // which grows monotonically to the middle, so once it is past what a
2382
- // double can hold it never comes back, and the largest run this can now
2383
- // take is the thousand-odd steps C(n, k) needs to cross that line.
2384
- 41: (args) => {
2385
- const n = Math.trunc(args[0].toNumber());
2386
- const r = Math.trunc(args[1].toNumber());
2387
- if (n < 0 || r < 0 || r > n) {
2388
- return errorValue("INVALID_RANGE", `combination: invalid n=${n}, r=${r} (require 0 <= r <= n)`);
2389
- }
2390
- const k = Math.min(r, n - r);
2391
- let result = 1;
2392
- for (let i = 0; i < k; i++) {
2393
- result = result * (n - i) / (i + 1);
2394
- if (!Number.isFinite(result)) {
2395
- return errorValue(
2396
- "COMBINATION_OVERFLOW",
2397
- `combination: C(${n}, ${r}) exceeds the maximum representable double (it passed it after ${i + 1} of ${k} steps)`
2398
- );
2399
- }
2400
- }
2401
- return numberValue(Math.round(result));
2402
- },
2403
- // average(...), arithmetic mean of any number of arguments. Backs the
2404
- // MathPhrases package's "average of X, Y, Z" (packages/mathphrases/).
2405
- 42: (args) => {
2406
- if (args.length === 0) return numberValue(0);
2407
- const sum = args.reduce((acc, a) => acc + a.toNumber(), 0);
2408
- return numberValue(sum / args.length);
2409
- },
2410
- // median(...), middle value; average of the two middle values for an
2411
- // even argument count.
2412
- 43: (args) => {
2413
- if (args.length === 0) return numberValue(0);
2414
- const sorted = args.map((a) => a.toNumber()).sort((a, b) => a - b);
2415
- const mid = Math.floor(sorted.length / 2);
2416
- return numberValue(
2417
- sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]
2418
- );
2419
- },
2420
- // total(...), sum of any number of arguments.
2421
- 44: (args) => numberValue(args.reduce((acc, a) => acc + a.toNumber(), 0)),
2422
- // count(...), number of arguments passed.
2423
- 45: (args) => numberValue(args.length),
2424
- // proportion(a, b, c) -> d such that a:b = c:d, i.e. d = c * (b/a)
2425
- // "A is to B as C is to what". Unit-aware via unifyUom: "5 km is to
2426
- // 500m as 5 cm is to what" unifies 5km/500m to a 10:1 ratio (500m ==
2427
- // 0.5km), so 5cm at the same ratio -> 0.5cm. Falls back to plain
2428
- // toNumber() ratios when the units aren't the same measure (unifyUom's
2429
- // own fallback) rather than guessing at an unsupported conversion.
2430
- 46: (args) => {
2431
- const [a, b, c] = args;
2432
- const { lv: aNum, rv: bNum } = unifyUom(a, b);
2433
- if (aNum === 0) {
2434
- return errorValue("PROPORTION_DIVIDE_BY_ZERO", `Cannot compute proportion: "${a.value}" is zero`);
2435
- }
2436
- const result = c.toNumber() * (bNum / aNum);
2437
- return c.type === 6 /* Uom */ ? uomValue(result, c.unit) : numberValue(result);
2438
- },
2439
- // clamp(value, lo, hi), restrict value to [lo, hi]. Backs
2440
- // "clamp X between Y and Z" / "clamp X from Y to Z".
2441
- 47: (args) => {
2442
- const value = args[0].toNumber();
2443
- const lo = args[1].toNumber();
2444
- const hi = args[2].toNumber();
2445
- if (lo > hi) {
2446
- return errorValue("INVALID_RANGE", `clamp: invalid range, ${lo} is greater than ${hi}`);
2447
- }
2448
- return numberValue(Math.min(Math.max(value, lo), hi));
2449
- },
2450
- // hex(n), Python/JS-style call-syntax hex formatting, e.g. hex(255) ->
2451
- // "0xFF". Distinct from the Converters package's `255 as hex` (see
2452
- // packages/converters/parselets/AsConverterParselet.ts): "as hex"
2453
- // produces a ValueType.Hex (a typed NUMBER that still participates in
2454
- // arithmetic, formatted specially on display), while hex() is a plain
2455
- // function call that returns an ordinary String value, matching
2456
- // Python's hex()/JS convention of a function returning display text,
2457
- // not a numeric type.
2458
- 48: (args) => hexValue(args[0].toNumber()),
2459
- // bin(n). Same call-syntax shape as hex() above, e.g. bin(10) -> "0b1010".
2460
- 49: (args) => hexValue(args[0].toNumber(), "bin"),
2461
- // int(x), coerce ANY value (Number, Percentage, Uom, String, Hex, ...)
2462
- // to a plain integer Number, truncating any fractional part toward
2463
- // zero (Math.trunc semantics: int(5.7) -> 5, int(-5.7) -> -5). Distinct
2464
- // from the Converters package's `x as number` (TO_NUMBER opcode),
2465
- // which only strips a unit/percentage wrapper and keeps any decimal
2466
- // part (e.g. "5.7 as number" -> 5.7), int() additionally truncates.
2467
- 50: (args) => numberValue(Math.trunc(args[0].toNumber())),
2468
- // ── Finance (packages/finance/) ──────────────────────────────────────
2469
- // All finance builtins preserve the principal/amount argument's Uom
2470
- // unit (e.g. a currency like "$") onto the result, matching
2471
- // ProportionParselet's convention (index 46, above), a plain-number
2472
- // input produces a plain-number result.
2473
- //
2474
- // `rate` arguments are always a decimal fraction (e.g. 0.07 for 7%)
2475
- // this is how "%" already normalizes everywhere else in this codebase
2476
- // (see packages/percentage/parselets/PercentParselet.ts: "7%" divides
2477
- // by 100 at parse time, producing a plain Number 0.07, not a distinct
2478
- // percentage type). Writing "at 7" instead of "at 7%" in a phrase form
2479
- // passes 7 as-is (not 0.07), the "%" is not implicit.
2480
- // compoundFutureValue(principal, rate, years) -> FV = P*(1+r)^years.
2481
- // Backs "compound interest on $P over Y years at R%" and the
2482
- // compoundInterest(principal, rate, years) function-call form.
2483
- 51: (args) => {
2484
- const principal = args[0].toNumber();
2485
- const rate = args[1].toNumber();
2486
- const years = args[2].toNumber();
2487
- if (1 + rate <= 0) {
2488
- return errorValue("INVALID_RATE", `compoundInterest: rate ${rate} makes (1 + rate) non-positive`);
2489
- }
2490
- const fv = principal * Math.pow(1 + rate, years);
2491
- return args[0].type === 6 /* Uom */ ? uomValue(fv, args[0].unit) : numberValue(fv);
2492
- },
2493
- // compoundInterestEarned(principal, rate, years) -> FV - principal, the
2494
- // interest-only portion. Backs "interest on $P over Y years at R%" and
2495
- // the interestEarned(principal, rate, years) function-call form.
2496
- 52: (args) => {
2497
- const principal = args[0].toNumber();
2498
- const rate = args[1].toNumber();
2499
- const years = args[2].toNumber();
2500
- if (1 + rate <= 0) {
2501
- return errorValue("INVALID_RATE", `interestEarned: rate ${rate} makes (1 + rate) non-positive`);
2502
- }
2503
- const interest = principal * (Math.pow(1 + rate, years) - 1);
2504
- return args[0].type === 6 /* Uom */ ? uomValue(interest, args[0].unit) : numberValue(interest);
2505
- },
2506
- // compoundInterestRate(principal, futureValue, years) -> the rate (as a
2507
- // decimal fraction) needed to grow principal to futureValue over years.
2508
- // Function-call only, no clean phrase form for a reverse calculation
2509
- // like this without inventing awkward new keywords, so it's scoped to
2510
- // compoundInterestRate(...) rather than a natural-language phrase.
2511
- 53: (args) => {
2512
- const principal = args[0].toNumber();
2513
- const futureValue = args[1].toNumber();
2514
- const years = args[2].toNumber();
2515
- if (principal <= 0 || futureValue <= 0) {
2516
- return errorValue("INVALID_RANGE", `compoundInterestRate: principal and futureValue must both be positive`);
2517
- }
2518
- if (years <= 0) {
2519
- return errorValue("INVALID_RANGE", `compoundInterestRate: years must be greater than 0`);
2520
- }
2521
- return numberValue(Math.pow(futureValue / principal, 1 / years) - 1);
2522
- },
2523
- // compoundInterestYears(principal, futureValue, rate) -> the number of
2524
- // years needed to grow principal to futureValue at a fixed rate.
2525
- // Function-call only, same reasoning as index 53 above.
2526
- 54: (args) => {
2527
- const principal = args[0].toNumber();
2528
- const futureValue = args[1].toNumber();
2529
- const rate = args[2].toNumber();
2530
- if (principal <= 0 || futureValue <= 0) {
2531
- return errorValue("INVALID_RANGE", `compoundInterestYears: principal and futureValue must both be positive`);
2532
- }
2533
- if (1 + rate <= 0 || rate === 0) {
2534
- return errorValue("INVALID_RATE", `compoundInterestYears: rate ${rate} is not usable (must be > -1 and not 0)`);
2535
- }
2536
- return numberValue(Math.log(futureValue / principal) / Math.log(1 + rate));
2537
- },
2538
- // loanRepayment(principal, rate, years, periodsPerYear), standard
2539
- // amortizing-loan repayment (mortgage formula), redistributed evenly
2540
- // across `periodsPerYear` periods/year: 365=daily, 12=monthly, 1=annual,
2541
- // 0=total over the life of the loan. The loan is ALWAYS amortized
2542
- // monthly internally (the standard mortgage convention) regardless of
2543
- // periodsPerYear, "daily"/"annual"/"total" are the same total
2544
- // repayment redistributed, not separately-amortized loans. Verified
2545
- // against real worked numbers (principal=$10,000, rate=6%, years=6):
2546
- // monthly $165.73, annual $1,988.75 (== total/years exactly), daily
2547
- // $5.45 (== total/(years*365)), total $11,932.48.
2548
- // Backs "daily/monthly/annual/total repayment on $P over Y years at R%".
2549
- 55: (args) => {
2550
- const principal = args[0].toNumber();
2551
- const rate = args[1].toNumber();
2552
- const years = args[2].toNumber();
2553
- const periodsPerYear = args[3].toNumber();
2554
- if (principal <= 0) return errorValue("INVALID_RANGE", `loanRepayment: principal must be positive`);
2555
- if (years <= 0) return errorValue("INVALID_RANGE", `loanRepayment: years must be positive`);
2556
- if (rate < 0) return errorValue("INVALID_RATE", `loanRepayment: rate must not be negative`);
2557
- if (periodsPerYear < 0) return errorValue("INVALID_RANGE", `loanRepayment: periodsPerYear must not be negative`);
2558
- const { totalRepayment } = amortizeLoan(principal, rate, years);
2559
- const result = periodsPerYear === 0 ? totalRepayment : totalRepayment / (years * periodsPerYear);
2560
- return args[0].type === 6 /* Uom */ ? uomValue(result, args[0].unit) : numberValue(result);
2561
- },
2562
- // loanInterest(principal, rate, years, periodsPerYear), the interest
2563
- // portion of index 55's repayment, same periodsPerYear convention.
2564
- // Backs "daily/monthly/annual/total interest on $P over Y years at R%".
2565
- 56: (args) => {
2566
- const principal = args[0].toNumber();
2567
- const rate = args[1].toNumber();
2568
- const years = args[2].toNumber();
2569
- const periodsPerYear = args[3].toNumber();
2570
- if (principal <= 0) return errorValue("INVALID_RANGE", `loanInterest: principal must be positive`);
2571
- if (years <= 0) return errorValue("INVALID_RANGE", `loanInterest: years must be positive`);
2572
- if (rate < 0) return errorValue("INVALID_RATE", `loanInterest: rate must not be negative`);
2573
- if (periodsPerYear < 0) return errorValue("INVALID_RANGE", `loanInterest: periodsPerYear must not be negative`);
2574
- const { totalInterest } = amortizeLoan(principal, rate, years);
2575
- const result = periodsPerYear === 0 ? totalInterest : totalInterest / (years * periodsPerYear);
2576
- return args[0].type === 6 /* Uom */ ? uomValue(result, args[0].unit) : numberValue(result);
2577
- },
2578
- // monthlyPayment(principal, rate, years), convenience 3-arg wrapper
2579
- // around index 55's monthly case, for direct function-call use without
2580
- // the periodsPerYear parameter (the task's minimum-ask function form).
2581
- 57: (args) => {
2582
- const principal = args[0].toNumber();
2583
- const rate = args[1].toNumber();
2584
- const years = args[2].toNumber();
2585
- if (principal <= 0) return errorValue("INVALID_RANGE", `monthlyPayment: principal must be positive`);
2586
- if (years <= 0) return errorValue("INVALID_RANGE", `monthlyPayment: years must be positive`);
2587
- if (rate < 0) return errorValue("INVALID_RATE", `monthlyPayment: rate must not be negative`);
2588
- const { monthlyPayment } = amortizeLoan(principal, rate, years);
2589
- return args[0].type === 6 /* Uom */ ? uomValue(monthlyPayment, args[0].unit) : numberValue(monthlyPayment);
2590
- },
2591
- // taxAdd(amount, rate) -> amount * (1 + rate), the tax-inclusive total.
2592
- // Backs the taxAdd() function-call form, whose name promises exactly this.
2593
- // The "tax on $X at R%" PHRASE does NOT use it, see index 86.
2594
- //
2595
- // No default rate is baked in anywhere, the caller always supplies one
2596
- // explicitly, since tax rates vary by region and change over time; this
2597
- // package makes no assumption about which rate applies.
2598
- 58: (args) => {
2599
- const amount = args[0].toNumber();
2600
- const rate = args[1].toNumber();
2601
- if (args[0].type === 6 /* Uom */) return scaleMoneyByPercent(args[0], args[0].unit, rate, 1);
2602
- return numberValue(amount * (1 + rate));
2603
- },
2604
- // taxRemove(amount, rate) -> amount / (1 + rate), extracts the
2605
- // pre-tax amount from a tax-INCLUSIVE total. Backs "tax off $X at R%" /
2606
- // "VAT off $X at R%".
2607
- 59: (args) => {
2608
- const amount = args[0].toNumber();
2609
- const rate = args[1].toNumber();
2610
- if (1 + rate <= 0) {
2611
- return errorValue("INVALID_RATE", `taxRemove: rate ${rate} makes (1 + rate) non-positive`);
2612
- }
2613
- if (args[0].type === 6 /* Uom */) {
2614
- return removeTaxExact(args[0], args[0].unit, rate) ?? uomValue(amount / (1 + rate), args[0].unit);
2615
- }
2616
- return numberValue(amount / (1 + rate));
2617
- },
2618
- // inflationAdjust(amount, fromYear, toYear) -- CPI-based inflation
2619
- // adjustment between two arbitrary years, using the bundled CPI-U
2620
- // table (packages/finance/data/CpiTable.ts -- see its doc comment for
2621
- // vintage/accuracy notes). Backs the function-call form
2622
- // inflationAdjust(...) (FunctionCallParselet's builtinNameToIndex map)
2623
- // and the "what is $X in fromYear worth in toYear" phrase form
2624
- // (InflationQueryParselet.ts). The two present-year-relative phrase
2625
- // forms ("what is $X from year" / "what was $X worth in year" / "$X
2626
- // in year dollars") and the flat-rate future-value projection ("value
2627
- // of $X in year assuming N% inflation") are collision-safe
2628
- // pluginFunctions instead, not indices here -- see
2629
- // packages/finance/parselets/InflationPluginFunctions.ts.
2630
- 60: (args) => {
2631
- const amount = args[0].toNumber();
2632
- const fromYear = args[1].toNumber();
2633
- const toYear = args[2].toNumber();
2634
- const ratio = inflationRatio(fromYear, toYear);
2635
- if (ratio === void 0) {
2636
- return errorValue(
2637
- "INFLATION_YEAR_OUT_OF_RANGE",
2638
- `inflationAdjust: fromYear ${fromYear} or toYear ${toYear} is outside the bundled CPI table's range (${CPI_MIN_YEAR}-${CPI_MAX_YEAR})`
2639
- );
2640
- }
2641
- const result = amount * ratio;
2642
- return args[0].type === 6 /* Uom */ ? uomValue(result, args[0].unit) : numberValue(result);
2643
- },
2644
- // root(n, x) -- the n-th root of x (Numi's `root n (x)` phrasing maps
2645
- // to this same call-style form; see FunctionCallParselet's name map).
2646
- // No native Math.root exists (unlike Math.cbrt for n=3 specifically),
2647
- // so this is Math.pow(x, 1/n) directly -- exact for n=2/n=3 modulo the
2648
- // usual floating-point pow() rounding, same precision class as every
2649
- // other builtin here.
2650
- 61: (args) => {
2651
- const n = args[0].toNumber();
2652
- const x = args[1].toNumber();
2653
- return numberValue(power(x, 1 / n));
2654
- },
2655
- // fact(n) / factorial(n) -- integer factorial. Deliberately rejects
2656
- // negative or non-integer input (factorial isn't defined for either
2657
- // without a gamma-function generalization this engine doesn't need) and
2658
- // caps at 170 -- Number.MAX_VALUE overflows to Infinity at 171!, so
2659
- // returning a silently-wrong (or silently-infinite) result past that
2660
- // point would be worse than a clear error.
2661
- 62: (args) => {
2662
- const n = args[0].toNumber();
2663
- if (!Number.isInteger(n) || n < 0) {
2664
- return errorValue("INVALID_FACTORIAL_INPUT", `fact: ${n} is not a non-negative integer`);
2665
- }
2666
- if (n > 170) {
2667
- return errorValue("FACTORIAL_OVERFLOW", `fact: ${n}! exceeds the maximum representable double (170! is the largest finite factorial)`);
2668
- }
2669
- let result = 1;
2670
- for (let i = 2; i <= n; i++) result *= i;
2671
- return numberValue(result);
2672
- },
2673
- // ── Matrix (packages/matrix/) ────────────────────────────────────────
2674
- // transpose(a)/det(a)/inv(a)/dot(a,b), reachable both via ordinary
2675
- // function-call syntax (this map) and via operator syntax (`^T`, `^-1`
2676
- //. See PrecedenceParser.ts's CARET special-casing, which emits these
2677
- // SAME indices) and `|a|` (abs()'s Matrix branch, index 1 above).
2678
- // Real linear-algebra work lives in vm/MatrixOps.ts, shared by both
2679
- // entry points rather than duplicated.
2680
- // transpose(a), for a Matrix, swaps rows/cols. A plain Number is its
2681
- // own transpose (a 1x1 "matrix" transposed is itself), matches this
2682
- // engine's existing convention of treating a scalar as a trivial 1x1
2683
- // matrix (see Value.ts's toNumber()/isNaN() 1x1 special case).
2684
- 63: (args) => args[0].type === 7 /* Matrix */ ? transpose(args[0].value) : args[0],
2685
- // det(a), determinant. A plain Number's "determinant" is itself (the
2686
- // determinant of a 1x1 matrix [x] is x).
2687
- 64: (args) => args[0].type === 7 /* Matrix */ ? determinant(args[0].value) : numberValue(args[0].toNumber()),
2688
- // inv(a), matrix inverse for a Matrix; for a plain Number, `1/x`
2689
- // (byte-identical to `Math.pow(x, -1)`, which is what `x^-1` computed
2690
- // before this feature existed. See PrecedenceParser.ts's `^-1`
2691
- // special-case doc comment for why this must stay exact).
2692
- 65: (args) => {
2693
- if (args[0].type === 7 /* Matrix */) return inverse(args[0].value);
2694
- return numberValue(1 / args[0].toNumber());
2695
- },
2696
- // dot(a, b), matrix product / scalar-broadcast, the SAME dispatch as
2697
- // the `*` operator between two matrices (vm/VM.ts's MUL case). Plain
2698
- // Number operands multiply directly; a Number mixed with a Matrix
2699
- // promotes the Number to a 1x1 Matrix first, so it broadcasts exactly
2700
- // like matrixMultiply()'s own 1x1-scalar case.
2701
- 66: (args) => {
2702
- const [a, b] = args;
2703
- if (a.type === 0 /* Number */ && b.type === 0 /* Number */) {
2704
- return numberValue(a.toNumber() * b.toNumber());
2705
- }
2706
- const toMatrix = (v) => v.type === 7 /* Matrix */ ? v.value : { rows: 1, cols: 1, data: [v.toNumber()], hasSymbolic: false };
2707
- return matrixMultiply(toMatrix(a), toMatrix(b));
2708
- },
2709
- // ── Symbolic algebra (packages/symbolic/) ──
2710
- // expand(expr), multiplying out every product and power. Reached only
2711
- // through its own parselet, never the builtinNameToIndex name map, so that
2712
- // `expand` keeps working as an ordinary variable name; see
2713
- // packages/symbolic/normalizer/SymbolicCallNormalizerRule.ts.
2714
- //
2715
- // A non-symbolic argument has nothing to expand and is returned unchanged,
2716
- // which is why this does not go through the CALL_BUILTIN symbolic dispatch:
2717
- // `expand(2+3)` is simply 5.
2718
- 67: (args) => {
2719
- const [value] = args;
2720
- if (value.type !== 9 /* Symbolic */) return value;
2721
- return symbolicToValue(expandSymbolic(value.value));
2722
- },
2723
- // factor(expr), writing a polynomial as a product of irreducible factors
2724
- // over the RATIONALS. x^2-2 and x^2+1 come back unchanged, which is the
2725
- // correct answer over that field rather than a failure; see symbolic/Factor.ts.
2726
- 68: (args) => {
2727
- const [value] = args;
2728
- if (value.type !== 9 /* Symbolic */) return value;
2729
- return symbolicToValue(factorSymbolic(value.value));
2730
- },
2731
- // solve(equation, variable), emitted by its own parselet as three stack
2732
- // values: the two sides of the equation, then the variable NAME as a
2733
- // String. Reading the name as a string rather than compiling it as a
2734
- // variable read is what lets `solve(x^2-4=0, x)` work without `x` existing.
2735
- 69: (args) => {
2736
- const [lhsValue, rhsValue, variableValue] = args;
2737
- if (variableValue?.type !== 3 /* String */) {
2738
- return errorValue("SOLVE_REQUIRES_VARIABLE_NAME", "solve's second argument must be the name of the unknown.");
2739
- }
2740
- return solveEquationValues(lhsValue, rhsValue, variableValue.value);
2741
- },
2742
- // der(expr, variable, order), the symbolic derivative. Genuinely symbolic
2743
- // rather than a finite difference, so it is exact.
2744
- 70: (args) => {
2745
- const [target, variableValue, orderValue] = args;
2746
- const variable = symbolicVariableName(variableValue, "der");
2747
- if (typeof variable !== "string") return variable;
2748
- const expression = valueToSymbolic(target);
2749
- if (expression === null) return errorValue("SYMBOLIC_NONFINITE_OPERAND", "der needs an expression with an exact value.");
2750
- return symbolicToValue(differentiate2(expression, variable, orderValue?.toNumber() ?? 1));
2751
- },
2752
- // integral(expr, variable), the indefinite integral without a constant of
2753
- // integration. Reports what it cannot do rather than approximating; see
2754
- // symbolic/Integral.ts.
2755
- 71: (args) => {
2756
- const [target, variableValue] = args;
2757
- const variable = symbolicVariableName(variableValue, "integral");
2758
- if (typeof variable !== "string") return variable;
2759
- const expression = valueToSymbolic(target);
2760
- if (expression === null) return errorValue("SYMBOLIC_NONFINITE_OPERAND", "integral needs an expression with an exact value.");
2761
- const result = integrate(expression, variable);
2762
- if (!result.ok) return errorValue("SYMBOLIC_INTEGRAL_UNSUPPORTED", `Cannot integrate this: ${result.reason}.`);
2763
- return symbolicToValue(result.value);
2764
- },
2765
- // taylor(expr, variable = point, degree).
2766
- 72: (args) => {
2767
- const [target, variableValue, pointValue, degreeValue] = args;
2768
- const variable = symbolicVariableName(variableValue, "taylor");
2769
- if (typeof variable !== "string") return variable;
2770
- const expression = valueToSymbolic(target);
2771
- const point = valueToSymbolic(pointValue);
2772
- if (expression === null || point === null || point.kind !== "const") {
2773
- return errorValue("SYMBOLIC_NONFINITE_OPERAND", "taylor needs an expression and an exact expansion point.");
2774
- }
2775
- return symbolicToValue(taylorSeries(expression, variable, point.value, degreeValue.toNumber()));
2776
- },
2777
- // jacobian(f1, f2, ...), variadic. The variables are not named: they come
2778
- // from the union of the functions' own unknowns, sorted, matching Calca.
2779
- 73: (args) => {
2780
- const functions = [];
2781
- for (const arg of args) {
2782
- const node = valueToSymbolic(arg);
2783
- if (node === null) return errorValue("SYMBOLIC_NONFINITE_OPERAND", "jacobian needs expressions with exact values.");
2784
- functions.push(node);
2785
- }
2786
- const variables = /* @__PURE__ */ new Set();
2787
- for (const fn of functions) for (const name of freeVariables(fn)) variables.add(name);
2788
- const sorted = [...variables].sort();
2789
- if (sorted.length === 0) return errorValue("SYMBOLIC_JACOBIAN_NO_VARIABLES", "jacobian needs at least one unknown to differentiate against.");
2790
- const rows = jacobian(functions, sorted);
2791
- const rowMajor = [];
2792
- for (const row of rows) {
2793
- for (const cell of row) rowMajor.push(symbolicToEntry(cell));
2794
- }
2795
- return matrixValue(rows.length, sorted.length, rowMajorToColumnMajor(rows.length, sorted.length, rowMajor));
2796
- },
2797
- // An imaginary literal, 3i. The parselet pushes the numeric part and this
2798
- // turns it into an exact imaginary value.
2799
- 74: (args) => symbolicToValue(complexNode(complex(RATIONAL_ZERO, rationalFromNumber(args[0].toNumber())))),
2800
- // conj(z), re(z) and im(z). Each folds immediately for a literal and stays
2801
- // symbolic for anything still carrying an unknown.
2802
- 75: (args) => applyComplexAccessor("conj", args[0]),
2803
- 76: (args) => applyComplexAccessor("re", args[0]),
2804
- 77: (args) => applyComplexAccessor("im", args[0]),
2805
- // cancel(expr), reducing a quotient of polynomials to lowest terms.
2806
- 78: (args) => {
2807
- const value = args[0];
2808
- if (value.type !== 9 /* Symbolic */) return value;
2809
- return symbolicToValue(cancelSymbolic(value.value));
2810
- },
2811
- // apart(expr), the partial-fraction decomposition of a rational function.
2812
- 79: (args) => {
2813
- const value = args[0];
2814
- if (value.type !== 9 /* Symbolic */) return value;
2815
- return symbolicToValue(apartSymbolic(value.value));
2816
- },
2817
- // taxIn(amount, rate) -> amount - amount/(1 + rate), the tax already
2818
- // contained in a tax-INCLUSIVE total. Backs "tax in/of/from $X at R%".
2819
- // The complement of taxRemove (index 59): the two sum to the gross amount.
2820
- 85: (args) => {
2821
- const amount = args[0].toNumber();
2822
- const rate = args[1].toNumber();
2823
- if (1 + rate <= 0) {
2824
- return errorValue("INVALID_RATE", `taxIn: rate ${rate} makes (1 + rate) non-positive`);
2825
- }
2826
- const tax = amount - amount / (1 + rate);
2827
- if (args[0].type === 6 /* Uom */) {
2828
- return taxInExact(args[0], args[0].unit, rate) ?? uomValue(tax, args[0].unit);
2829
- }
2830
- return numberValue(tax);
2831
- },
2832
- // taxOn(amount, rate) -> amount * rate, the tax itself.
2833
- //
2834
- // The "tax on $X at R%" phrase used to compile to taxAdd (index 58) and
2835
- // answer $345.00 for "tax on $300 at 15%". Soulver answers $45.00, and
2836
- // "the tax on $300" is the tax, not the bill. The total is "$300 + 15%",
2837
- // which reads as a relative increase (see PercentParselet.ts), or
2838
- // taxAdd(300, 0.15) for the function form.
2839
- 86: (args) => {
2840
- const amount = args[0].toNumber();
2841
- const rate = args[1].toNumber();
2842
- if (args[0].type === 6 /* Uom */) return scaleMoneyExact(args[0], rate, args[0].unit);
2843
- return numberValue(amount * rate);
2844
- },
2845
- // ── Degree-taking trig (sind/cosd/tand and the inverses) ──────────────
2846
- // The "d" spellings take and return degrees rather than radians, which is
2847
- // the convention every scientific calculator uses. sin(90 degrees) is the
2848
- // other way to say the same thing; both exist because both get typed.
2849
- 87: (args) => numberValue(Math.sin(args[0].toNumber() * Math.PI / 180)),
2850
- 88: (args) => numberValue(Math.cos(args[0].toNumber() * Math.PI / 180)),
2851
- 89: (args) => numberValue(Math.tan(args[0].toNumber() * Math.PI / 180)),
2852
- 90: (args) => numberValue(Math.asin(args[0].toNumber()) * 180 / Math.PI),
2853
- 91: (args) => numberValue(Math.acos(args[0].toNumber()) * 180 / Math.PI),
2854
- 92: (args) => numberValue(Math.atan(args[0].toNumber()) * 180 / Math.PI),
2855
- // daysCount(n) -> n labelled as days. "days in Q3" is a count of days
2856
- // and should say so; a bare 92 loses what was being counted.
2857
- 93: (args) => uomValue(args[0].toNumber(), "days"),
2858
- // asTwoUnits(value, majorUnit, minorUnit) -> "12 min 30 s".
2859
- //
2860
- // "12.5 minutes in minutes and seconds" asks for one quantity split
2861
- // across two units, which every other conversion path cannot express:
2862
- // they each produce a single number in a single unit.
2863
- //
2864
- // The whole part goes to the major unit and the remainder to the minor,
2865
- // so nothing is lost. A pair that is not ordered major-then-minor, or
2866
- // that spans two different measures, reports rather than guessing.
2867
- 94: (args) => {
2868
- const major = typeof args[1]?.value === "string" ? args[1].value : void 0;
2869
- const minor = typeof args[2]?.value === "string" ? args[2].value : void 0;
2870
- if (major === void 0 || minor === void 0) {
2871
- return errorValue("UNKNOWN_UNIT", 'both units have to be named, as in "12.5 minutes in minutes and seconds"');
2872
- }
2873
- const majorEntry = UNIT_TABLE[major.toLowerCase()];
2874
- const minorEntry = UNIT_TABLE[minor.toLowerCase()];
2875
- if (majorEntry === void 0 || minorEntry === void 0) {
2876
- return errorValue("UNKNOWN_UNIT", `${major} and ${minor}: one of these is not a unit`);
2877
- }
2878
- if (majorEntry[0] !== minorEntry[0]) {
2879
- return errorValue("INCOMPATIBLE_UNITS", `${major} and ${minor} measure different things`);
2880
- }
2881
- if (minorEntry[1] >= majorEntry[1]) {
2882
- return errorValue("INCOMPATIBLE_UNITS", `${major} and ${minor}: name the larger unit first`);
2883
- }
2884
- const source = args[0];
2885
- const sourceEntry = source.type === 6 /* Uom */ && source.unit !== void 0 ? UNIT_TABLE[source.unit.toLowerCase()] : void 0;
2886
- const inBase = source.toNumber() * (sourceEntry?.[1] ?? majorEntry[1]);
2887
- const majorCount = Math.floor(inBase / majorEntry[1]);
2888
- const minorCount = Math.round((inBase - majorCount * majorEntry[1]) / minorEntry[1] * 1e3) / 1e3;
2889
- return stringValue(`${majorCount} ${major} ${minorCount} ${minor}`);
2890
- },
2891
- // makeRate(value, denominatorUnit) -> value per that unit.
2892
- //
2893
- // `3 hours / day` is a rate, `3 hours / 3 days` is a division. The
2894
- // difference is whether a number was written in the denominator, which
2895
- // is decided at parse time, so this only ever receives the rate case.
2896
- //
2897
- // Building the rate directly rather than dividing by an implied 1 is the
2898
- // whole point: a division makes same-measure units cancel, which turned
2899
- // `3 hours / day` into 0.125 when that shortcut was tried.
2900
- 95: (args) => {
2901
- const source = args[0];
2902
- const denominator = String(args[1].value);
2903
- const numerator = source.type === 6 /* Uom */ && source.unit !== void 0 ? source.unit : "";
2904
- if (numerator.includes("/")) {
2905
- return errorValue("INVALID_RATE_UNIT", `${numerator}/${denominator}: that is already a rate`);
2906
- }
2907
- return uomValue(source.toNumber(), `${numerator}/${denominator}`);
2908
- },
2909
- // atRate(quantity, rate) -> whichever of the two the question implies.
2910
- //
2911
- // 30 hours at $30/hour $900 a duration at a price per duration
2912
- // $500 at $20/hour 25 hours money at a price per duration
2913
- //
2914
- // Both are written with the same word and mean opposite operations. Which
2915
- // one applies is decided by which half of the rate the left side matches:
2916
- // match the denominator and you are buying that many, match the numerator
2917
- // and you are asking how many it buys.
2918
- 96: (args) => {
2919
- const left = args[0];
2920
- const rate = args[1];
2921
- if (rate.type !== 6 /* Uom */ || rate.unit === void 0 || !rate.unit.includes("/")) {
2922
- return errorValue("INVALID_RATE", 'at: the right-hand side has to be a rate, as in "$30/hour"');
2923
- }
2924
- const slash = rate.unit.indexOf("/");
2925
- const numerator = rate.unit.slice(0, slash);
2926
- const denominator = rate.unit.slice(slash + 1);
2927
- const leftUnit = left.type === 6 /* Uom */ ? left.unit : void 0;
2928
- const denominatorEntry = UNIT_TABLE[denominator.toLowerCase()];
2929
- const leftEntry = leftUnit === void 0 ? void 0 : UNIT_TABLE[leftUnit.toLowerCase()];
2930
- if (leftEntry !== void 0 && denominatorEntry !== void 0 && leftEntry[0] === denominatorEntry[0]) {
2931
- const inDenominator = left.toNumber() * leftEntry[1] / denominatorEntry[1];
2932
- const total = inDenominator * rate.toNumber();
2933
- return numerator === "" ? numberValue(total) : uomValue(total, numerator);
2934
- }
2935
- if (leftUnit !== void 0 && leftUnit === numerator) {
2936
- const count = left.toNumber() / rate.toNumber();
2937
- return uomValue(count, pluraliseUnit(denominator, count));
2938
- }
2939
- if (leftUnit === void 0) {
2940
- const total = left.toNumber() * rate.toNumber();
2941
- return numerator === "" ? numberValue(total) : uomValue(total, numerator);
2942
- }
2943
- return errorValue("INCOMPATIBLE_UNITS", `at: ${leftUnit} matches neither side of ${rate.unit}`);
2944
- },
2945
- // ── Investments (packages/finance/) ────────────────────────────────────
2946
- // compoundFutureValueEvery(principal, rate, years, periodsPerYear)
2947
- // FV = P(1 + r/n)^(n·y). Index 51 is the same formula with n fixed at 1;
2948
- // this one backs "compounding monthly"/"quarterly"/"daily"/"weekly".
2949
- // Kept separate rather than widening 51, because 51 is also the public
2950
- // compoundInterest(principal, rate, years) call and its arity is part of
2951
- // that contract.
2952
- 80: (args) => {
2953
- const principal = args[0].toNumber();
2954
- const rate = args[1].toNumber();
2955
- const years = args[2].toNumber();
2956
- const perYear = args[3].toNumber();
2957
- if (perYear <= 0) {
2958
- return errorValue("INVALID_RATE", `compounding: ${perYear} periods per year is not a period`);
2959
- }
2960
- if (1 + rate / perYear <= 0) {
2961
- return errorValue("INVALID_RATE", `compounding: rate ${rate} makes each period non-positive`);
2962
- }
2963
- const fv = principal * Math.pow(1 + rate / perYear, perYear * years);
2964
- return args[0].type === 6 /* Uom */ ? uomValue(fv, args[0].unit) : numberValue(fv);
2965
- },
2966
- // compoundInterestEarnedEvery(principal, rate, years, periodsPerYear)
2967
- // The interest-only portion of index 80, i.e. FV - P.
2968
- 81: (args) => {
2969
- const principal = args[0].toNumber();
2970
- const rate = args[1].toNumber();
2971
- const years = args[2].toNumber();
2972
- const perYear = args[3].toNumber();
2973
- if (perYear <= 0 || 1 + rate / perYear <= 0) {
2974
- return errorValue("INVALID_RATE", `compounding: rate ${rate} over ${perYear} periods per year is not usable`);
2975
- }
2976
- const interest = principal * (Math.pow(1 + rate / perYear, perYear * years) - 1);
2977
- return args[0].type === 6 /* Uom */ ? uomValue(interest, args[0].unit) : numberValue(interest);
2978
- },
2979
- // presentValue(futureValue, rate, years) -> FV / (1 + r)^y, what a sum
2980
- // promised in the future is worth today. The inverse of index 51.
2981
- 82: (args) => {
2982
- const future = args[0].toNumber();
2983
- const rate = args[1].toNumber();
2984
- const years = args[2].toNumber();
2985
- if (1 + rate <= 0) {
2986
- return errorValue("INVALID_RATE", `presentValue: rate ${rate} makes (1 + rate) non-positive`);
2987
- }
2988
- const pv = future / Math.pow(1 + rate, years);
2989
- return args[0].type === 6 /* Uom */ ? uomValue(pv, args[0].unit) : numberValue(pv);
2990
- },
2991
- // returnOnInvestment(invested, returned) -> (returned - invested) /
2992
- // invested, the gain as a multiple of what was put in. $500 in and $1,500
2993
- // out is 2x, not 3x: ROI conventionally measures the profit against the
2994
- // cost, so doubling your money is 1x return and tripling it is 2x. The
2995
- // money multiple (3x here) is a different figure; `$1,500 / $500` gives it.
2996
- 83: (args) => {
2997
- const invested = args[0].toNumber();
2998
- const returned = args[1].toNumber();
2999
- if (invested === 0) {
3000
- return errorValue("INVALID_RATE", "roi: nothing was invested, so there is no return on it");
3001
- }
3002
- return numberValue((returned - invested) / invested);
3003
- },
3004
- // annualisedReturn(invested, returned, years) -> CAGR, the constant
3005
- // yearly rate that turns `invested` into `returned` over `years`:
3006
- // (returned/invested)^(1/years) - 1. Returned as a Percentage so it
3007
- // renders "13.99%" rather than 0.1399.
3008
- 84: (args) => {
3009
- const invested = args[0].toNumber();
3010
- const returned = args[1].toNumber();
3011
- const years = args[2].toNumber();
3012
- if (invested <= 0) {
3013
- return errorValue("INVALID_RATE", "annual return: the amount invested must be positive");
3014
- }
3015
- if (years <= 0) {
3016
- return errorValue("INVALID_RATE", "annual return: the period must be longer than zero");
3017
- }
3018
- if (returned <= 0) {
3019
- return errorValue("INVALID_RATE", "annual return: nothing was returned, so there is no annual rate");
3020
- }
3021
- return percentageValue(Math.pow(returned / invested, 1 / years) - 1);
3022
- },
3023
- // roundToPlaces(value, places) -> value rounded to that many decimal
3024
- // places, backing `<value> to <n> dp` (converters/parselets/
3025
- // RoundingParselets.ts).
3026
- //
3027
- // It exists because the obvious bytecode for it, "multiply by 10^p, round,
3028
- // divide by 10^p", is only safe for values small enough that the multiply
3029
- // is exact. `1e21 to 2 dp` came back as 999999999999999900000: 1e21 has no
3030
- // fractional part to round at all, and the round trip through 1e23 was
3031
- // pure loss. Asking for fewer decimal places than a number has cannot
3032
- // change it, so a value that is already whole is returned untouched.
3033
- 97: (args) => roundToPlaces(args[0], args[1].toNumber())
3034
- };
3035
- function applyComplexAccessor(name, value) {
3036
- const node = valueToSymbolic(value);
3037
- if (node === null) return errorValue("SYMBOLIC_NONFINITE_OPERAND", name + " needs a value with an exact number.");
3038
- return symbolicToValue(callNode(name, [node]));
3039
- }
3040
- function symbolicVariableName(value, verb) {
3041
- if (value?.type !== 3 /* String */) {
3042
- return errorValue("SYMBOLIC_REQUIRES_VARIABLE_NAME", `${verb} needs the name of an unknown.`);
3043
- }
3044
- return value.value;
3045
- }
3046
- function amortizeLoan(principal, annualRate, years) {
3047
- const n = years * 12;
3048
- const rMonthly = annualRate / 12;
3049
- const monthlyPayment = rMonthly === 0 ? principal / n : principal * rMonthly / (1 - Math.pow(1 + rMonthly, -n));
3050
- const totalRepayment = monthlyPayment * n;
3051
- const totalInterest = totalRepayment - principal;
3052
- return { monthlyPayment, totalRepayment, totalInterest };
3053
- }
3054
- var pluginFunctionRegistry = defaultEngineContext.pluginFunctions;
3055
- var MAX_PLUGIN_FUNCTION_INDEX = 255;
3056
- var nextPluginFunctionIndex = 0;
3057
- function allocatePluginFunctionIndex() {
3058
- if (nextPluginFunctionIndex > MAX_PLUGIN_FUNCTION_INDEX) {
3059
- throw ErrorFactory.config(
3060
- "PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED",
3061
- `allocatePluginFunctionIndex: pool exhausted (max ${MAX_PLUGIN_FUNCTION_INDEX + 1} allocations).`
3062
- );
3063
- }
3064
- return nextPluginFunctionIndex++;
3065
- }
3066
- var asConverterRegistry = /* @__PURE__ */ new Map();
3067
- function registerAsConverter(name, handler) {
3068
- const key = name.toLowerCase();
3069
- const existing = asConverterRegistry.get(key);
3070
- if (existing && existing !== handler) {
3071
- console.warn(`[asConverterRegistry] Converter name "${key}" is already registered \u2014 overwriting.`);
3072
- }
3073
- asConverterRegistry.set(key, handler);
3074
- }
3075
- function unregisterAsConverter(name) {
3076
- asConverterRegistry.delete(name.toLowerCase());
3077
- }
3078
-
3079
- // src/vm/GlobalVariableStore.ts
3080
- var _GlobalVariableStore = class _GlobalVariableStore {
3081
- constructor() {
3082
- this.values = /* @__PURE__ */ new Map();
3083
- this.listeners = /* @__PURE__ */ new Set();
3084
- this.notifyDepth = 0;
3085
- }
3086
- get(name) {
3087
- return this.values.get(name);
3088
- }
3089
- has(name) {
3090
- return this.values.has(name);
3091
- }
3092
- /**
3093
- * Last-write-wins: any document may call this for any name at any time.
3094
- * Notifies listeners synchronously, within the same call, before
3095
- * returning, so that ThreeTierEvaluator's dirty-marking (a listener)
3096
- * and GlobalVariableAsyncResolver's first-write promise (also a
3097
- * listener) both observe the new value immediately, no microtask delay.
3098
- *
3099
- * A write that does not CHANGE the stored value notifies nobody. This
3100
- * is not just an optimisation, it is what stops a re-evaluation cycle
3101
- * from sustaining itself. Every listener re-runs work in response to a
3102
- * write (ThreeTierEvaluator marks dependent lines dirty; the playground
3103
- * worker refreshes other documents), and those re-runs re-execute the
3104
- * very STORE_GLOBAL_VAR opcode that produced this write. Re-evaluating
3105
- * an unchanged `global :x = 5` line therefore used to re-notify, which
3106
- * re-triggered the listeners, which re-evaluated... bounded only by
3107
- * MAX_NOTIFY_DEPTH below, and only in DEPTH, so with more than one
3108
- * writer the work per keystroke grew exponentially. Nothing observable
3109
- * changed, so there is nothing for a listener to react to.
3110
- */
3111
- set(name, value) {
3112
- const previous = this.values.get(name);
3113
- this.values.set(name, value);
3114
- if (previous !== void 0 && sameValue(previous, value)) return;
3115
- this.notify(name, value);
3116
- }
3117
- notify(name, value) {
3118
- if (this.notifyDepth >= _GlobalVariableStore.MAX_NOTIFY_DEPTH) return;
3119
- this.notifyDepth++;
3120
- try {
3121
- for (const listener of this.listeners) listener(name, value);
3122
- } finally {
3123
- this.notifyDepth--;
3124
- }
3125
- }
3126
- /**
3127
- * Subscribe to every global-variable write (all names, callers filter
3128
- * for the name(s) they care about). Returns an unsubscribe function;
3129
- * callers MUST invoke it when disposing (e.g. ThreeTierEvaluator's
3130
- * terminateWorker()) to avoid leaking listeners for closed documents.
3131
- */
3132
- subscribe(listener) {
3133
- this.listeners.add(listener);
3134
- return () => {
3135
- this.listeners.delete(listener);
3136
- };
3137
- }
3138
- /**
3139
- * Full reset, test-only. Never called from production code paths;
3140
- * globals must outlive any single engine's own clear()/dispose cycle.
3141
- * Tests MUST call this in beforeEach/afterEach since this is a
3142
- * module-level singleton whose state and listeners otherwise leak
3143
- * across test cases and files.
3144
- */
3145
- clear() {
3146
- this.values.clear();
3147
- this.listeners.clear();
3148
- this.notifyDepth = 0;
3149
- }
3150
- };
3151
- /**
3152
- * Guards against runaway cross-document write cycles: doc A's write
3153
- * notifies doc B, whose dirty line, once evaluated, writes a global
3154
- * that notifies doc C, ... eventually back to A. Same philosophy as the
3155
- * VM's own instruction-limit safety net: stop propagating past the
3156
- * limit rather than let a genuine cycle recurse unboundedly. The store
3157
- * itself is left in a well-defined state either way. This only bounds
3158
- * *notification* depth, never the value actually stored.
3159
- */
3160
- _GlobalVariableStore.MAX_NOTIFY_DEPTH = 64;
3161
- var GlobalVariableStore = _GlobalVariableStore;
3162
- function sameValue(a, b) {
3163
- if (a.type !== b.type) return false;
3164
- if (a.unit !== b.unit) return false;
3165
- if ((a.timedOut ?? false) !== (b.timedOut ?? false)) return false;
3166
- const av = a.value;
3167
- const bv = b.value;
3168
- if (Array.isArray(av) || Array.isArray(bv)) {
3169
- if (!Array.isArray(av) || !Array.isArray(bv)) return false;
3170
- if (av.length !== bv.length) return false;
3171
- for (let i = 0; i < av.length; i++) {
3172
- if (!Object.is(av[i], bv[i])) return false;
3173
- }
3174
- return true;
3175
- }
3176
- return Object.is(av, bv);
3177
- }
3178
- var sharedGlobalVariableStore = new GlobalVariableStore();
3179
- function globalDagKey(name) {
3180
- return `global:${name}`;
3181
- }
3182
-
3183
- export { CPI_MAX_YEAR, CPI_MIN_YEAR, OpRegistry, SYMBOLIC_NATIVE_BUILTINS, adjustForInflation, allocatePluginFunctionIndex, asConverterRegistry, bigIntDivisionByZero, binaryOp, builtinFunctions, compareBigIntOperands, compareRationalOperands, compareUom, createEngineContext, defaultEngineContext, describeConversionMismatch, exactRationalOp, globalDagKey, incomparableUnitsError, moneyExactMagnitude, pluginFunctionRegistry, power, registerAsConverter, scaleMoneyByPercent, scaleMoneyExact, sharedGlobalVariableStore, sharedOpRegistry, solveEquationValues, solveForVariable, symbolicBuiltin, symbolicNeg, symbolicPow, toBigIntOperand, uncertainOp, unifyUom, unregisterAsConverter };
3184
- //# sourceMappingURL=chunk-NKW7LKYU.js.map
3185
- //# sourceMappingURL=chunk-NKW7LKYU.js.map