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