From b287ee650a2ec24230e76d57f8275546cbec1753 Mon Sep 17 00:00:00 2001 From: gauravchawhan <117282267+gauravchawhan@users.noreply.github.com> Date: Mon, 14 Oct 2024 13:39:09 +0530 Subject: [PATCH] Updated code (#1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: Find eigenvectors of defective matrices (#3037) * fix: Find eigenvectors of defective matrices Previously, attempting to take the `eigs` of any defective matrix was doomed to fail in an attempt to solve a singular linear system. This PR detects the situation (as best as it can given the inherent numerical instability of the current methods used) and handles it. Note that in such cases, it's not possible to return a square matrix whose columns are the eigenvectors corresponding to the returned eigenvalues. In light of that fact and issue #3014, this PR also changes the return value of `eigs` so that the eigenvectors are passed back in a property `eigenvectors` which is an array of plain objects `{value: e, vector: v}`. Note that this PR makes the ancillary changes of correcting the spelling of the filename which was "realSymetric.js," and replacing the now-unnecessary auxiliary function "createArray" therein with `Array(size).fill(element)`. The rationale for performing these changes not strictly related to the issues at hand is that this file is rarely touched and with the level of maintenance hours we have at hand, it's more efficient to do these small refactorings in parallel with the actual bugfixes, which are orthogonal and so will not be obfuscated by this refactor. Note `git diff` does properly track the file name change. However, it also makes a potentially more pervasive change: in order for the numerically-sensitive algorithm to work, it changes the condition on when two very close (double) numbers are "nearlyEqual" from differing by less than DBL_EPSILON to differing by less than or equal to DBL_EPSILON. Although this may change other behaviors than the ones primarily being addressed, I believe it is an acceptable change because (a) It preserves all tests. (b) DBL_EPSILON is well below the standard config.epsilon anyway (c) I believe there are extant issues noting the odd/inconsistent behavior of nearlyEqual near 0 anyway, so I believe this will be overhauled in the future in any case. If so, the eigenvector computation will make a good test that a future nearlyEqual algorithm is working well. To be clear, the direct motivation for the change is that there are multiple cases in the eigenvector computation in which a coefficient that is "supposed" to be zero comes out to precisely DBL_EPSILON, which is fairly unsurprising given that these coefficients are produced by subtracting an eigenvalue from a diagonal entry of a matrix, which is likely to be essentially equal to that eigenvalue. As many tests of defective matrices as I could readily find by web searching have been added as unit tests (and one more in the typescript type testing). An additional case I found still fails, but in the _eigenvalue_ computation rather than the _eigenvector_ search, so that was deemed beyond the scope of this PR and has been filed as issue #3036. Resolves #2879. Resolves #2927. Resolves #3014. * refactor: remove comma that lint now doesn't like * test: add a test for eigs with a precision argument * feat: Use simple shifts in QR eigenvalue iterations that improve convergence Although we might want to use better shifts in the future, we might just use a library instead. But for now I think this: Resolves #2178. Also responds to the review feedback provided in PR #3037. * docs: update history * fix: #3074 improve error message when using function `max` in `derivative` * fix: #3073 parsing quotes inside a string * fix: #2027 cannot use named operators like `to` or `mod` as property name * chore: update devDependencies * chore: run `npm audit fix` * chore: publish v11.11.2 * Drop official support for Node.js 14 and 16 * fix: change toTex variable and function assignment from `:=` to `=` (see #2980, #3032) * Update history * docs: fix typo in `p.set` example in the documentation of matrices (#3080) * feat: Add option to eigs() to turn off eigenvector computation (#3057) * feat: Add option to eigs() to turn off eigenvector computation For large matrices, the eigenvector computation can be noticeably expensive and so it's worthwhile to have a way to turn it off if the eigenvectors will not be used. Resolves #2180. * fix: Add test for precision in options arg of eigs And also a fix for a small bug that the new test uncovered. * test: check eigs with matrix and options * refactor: remove dead code from complexEigs.js * fix: add new signatures of eigs to typescript * test: ensure eigenvectors property not present with eigenvectors: false option * fix: correct balancing code in complexEigs * Fix: #3073 escaping in strings (#3082) * chore: refactor parsing strings to not rely on `JSON.parse` * fix: #3073 function `format` not escaping control characters and double quotes in strings * chore: add more unit tests * feat: implement subtractScalar (#3081, #2643) * added subtractScaler * added subtractScaler missing entries * added test cases for 2 or more parameters, test for subtractScalar instead fo subtract * replaced subtract with subtractScalar whereever possible --------- Co-authored-by: Jos de Jong * fix: function `clone` not throwing an error in case of an unsupported type like a function * chore: make the unit test more robust * fix: #2960 add type definition of function `symbolicEqual` (#3035) * chore: update devDependencies * chore: publish v11.12.0 * fix: #2919 TypeScript types not working with NodeNext module resolution (#3079) * docs: update deprecation messages * chore: publish v12.0.0 * chore: update history (forgot to mention a feature in v12) * fix: #3088 error in the description of the return type of `pickRandom` * fix #3087: extend function `mod` with support for negative divisors in when using `BigNumber` or `Fraction` * fix #3092: a typo in an error message when converting a string into a number * fix #3094: function `derivative` mutates the input expression when it fails * feat: extend function `round` with support for units (#3095) * fix #2761: implement support for units in function `round` (WIP) * fix #2761: extend function `round` with support for units * docs: describe all signatures in the docs of function round * chore: fix linting issue * chore: remove less-useful signatures for round with units and matrices * chore: update devDependencies * chore: publish v12.1.0 * docs: update the release date in history.md * fix: #3096 embedded docs of `eigs` throwing an error * chore: update history * fix: accidentally passing a scope as third _and_ fourth argument to raw functions * feat: lazy evaluation of and, or, &, | (#3101, #3090) * If fn has rawArgs set, pass unevaluated args * Add shared helper function for evaluating truthiness * Add and & or transform functions for lazy evaluation * Add lazy evaluation of bitwise & and | operators * Add unit tests for lazy evaluation * Add lazy evaluation note to docs * Move documentation to Syntax page * Replace `testCondition()` with test evaluation of logical function itself * Use `isCollection()` to simplify bitwise transform functions * fix: do not copy scope in raw OperatorNode, test lazy operators scope * fix: linting issues --------- Co-authored-by: Brooks Smith * docs: update history * chore: update devDependencies * chore: publish `v12.2.0` * fix: #3109 method `Node.toHTML` not accepting a custom `handler` * chore: upgrade node and Github actions versions for CI * chore: upgrade devDependencies * chore: publish v12.2.1 * chore: oopsie, update version number in version.js * chore: up version number, and pin fraction.js at v4.3.4 * chore: publish v12.2.1 * docs: update maintenance badge to 2024 * docs: fix the github sponsors badge * Support new metric prefixes: Q, R, r, and q (#3113) * added Q, R, r, q metrix prefixes * tests added for new prefixes * removed duplicate tests * maybe square and cubic tests will bump code cov into the positive * Check numeric value --------- Co-authored-by: Jos de Jong * chore: update history * docs: change 2023 to 2024 * Unitless quantity conversion bug (#3117) * Add test for conversion to unitless quantity * Avoid access to missing array index * Also check that other.units is not empty * Add test for abs of dimensionless unit * Fix: avoid access to missing units array index --------- Co-authored-by: Jos de Jong * chore: update history * fix `toSI()` wrongly converting `degC` (#3118) * Add new test for degC toSI * Convert value using to() if needed * Only set ret.value = null when it is not already null --------- Co-authored-by: Jos de Jong * chore: update history * chore: update devDependencies * chore: publish v12.3.0 * chore: run `npm audit fix` * Infer types of arguments more precisely (#3123) * Prefer inferring types of nodes as tuples * Implement for IndexNode * Test for types * Use tuple type for array node --------- Co-authored-by: Jos de Jong * chore: update history * CodeEditorExample (#3027) * broadcasting * Simplified broadcasting * Updated for broadcasting * Changed to camel case * Camel case and auto formating * Added comments * Skip if matrices have the same size * Fixed issue with undefined variable missing dot in `A._size` * Implemented broadcasting in all functions * Added helper functions * Added function to check for broadcasting rules * Tests for broadcasted arithmetic * Fixed issue with matrix the size of a vector * Documented and updated broadcasting * Included broadcast.test * Included math to syntax when missing * Add code editor example * Vite mini project * Initial example * added alpine debounce * Fixed display * Added parser.clear * Added mathjs-language * Made module to get expressions * Added custom events * Issue with help formatting * Simplified help format * Restored package.json * removed unneded icons * Added readme file * Fixed versions * Commented getExpressions * Documented main.js * Fixed title * Fixed alpine version * Removed AlpineJS * Added documentation and renamed variables for clarity * Fixed naming errors --------- Co-authored-by: David Contreras Co-authored-by: Jos de Jong * chore: minor refinement in the `code editor` example * chore: update HISTORY.md * fix: #3114 build warnings related to a number of wrong `/* #__PURE__ */` annotations * chore: do not output documentation warnings unless running with a `--debug-docs` flag * docs: update authors * Fixed issue with long lines in Code Editor Example (#3130) * broadcasting * Simplified broadcasting * Updated for broadcasting * Changed to camel case * Camel case and auto formating * Added comments * Skip if matrices have the same size * Fixed issue with undefined variable missing dot in `A._size` * Implemented broadcasting in all functions * Added helper functions * Added function to check for broadcasting rules * Tests for broadcasted arithmetic * Fixed issue with matrix the size of a vector * Documented and updated broadcasting * Included broadcast.test * Included math to syntax when missing * Add code editor example * Vite mini project * Initial example * added alpine debounce * Fixed display * Added parser.clear * Added mathjs-language * Made module to get expressions * Added custom events * Issue with help formatting * Simplified help format * Restored package.json * removed unneded icons * Added readme file * Fixed versions * Commented getExpressions * Documented main.js * Fixed title * Fixed alpine version * Removed AlpineJS * Added documentation and renamed variables for clarity * Fixed naming errors * Fixed issue with long lines * Edge case where multiple expressions are on the same line not ending in ";" --------- Co-authored-by: David Contreras Co-authored-by: Jos de Jong * docs: #3145 fix documentation about REPL, it does require a build step nowadays * fix: #3142 support BigNumber values for the options of function `format`: `precision`, `wordSize`, `lowerExp`, `upperExp` * Improve type definitions of function `hypot` (#3144) * Addressed silentmissile's comment in https://github.com/josdejong/mathjs/issues/3125 * Added method overload to index.d.ts, have to revert commit due to changes to package-lock.json with using npm install to run the unit tests & lint tests * chore: update HISTORY.md * fix: #3141 `help(config)` altering the actual `config` when evaluating the examples * chore: update devDependencies * chore: publish `v12.3.1` * chore: add a benchmark to get a feel for how fast scope variables are resolved * chore: fix linting issue * Fix not being able to use `and` and `or` inside a function definition (#3150) * chore: write unit tests using `and` and `or` inside a function definition (WIP) * fix: #3143 fix scope issues in rawArgs functions by implementing a `PartitionedMap` * fix: add more unit tests for `ObjectWrappingMap` * fix: don't let `ObjectWrappingMap` and `PartitionedMap` extend `Map` (risk of having non-overwritten methods) * docs: update docs about `rawArgs` functions * chore: update devDependencies * chore: publish v12.3.2 * chore: publish v12.3.2 * fix: #3155 remove an outdated section about complex numbers from the docs * docs: describe `getAllAsMap` in the Parser docs (#3158) * chore: update history * Determinant with small numbers fix (#3139) * feat: trailing commas in matrices (#3154) * chore: update history * docs: fix broken example in the documentation about matrices (see #3159) * fix: `PartitionedMap` and `ObjectWrappingMap` missing a property `Symbol.iterator` * fix: linting issue * fix: mode signature return types (#3153) * fix: mode type signatures * Add ts tests for mode * Add assertions mode type tests * Update author Rich in AUTHORS file --------- Co-authored-by: Rich Martinez Co-authored-by: Jos de Jong * chore: update history * feat: improve the performance f `multiply` by adding matrix type inferencing (#3149) * added type inference * added back accidentally removed return statement and made it so that the explicitly defined type is returned at the end * made sure that mixed types are ignored in the process data types check * fixed issue with undefined _data for SparseMatrix and linting issues * simplified syntax and added type inferencing to src/type/matrix/utils and src/function/matrix/dot.js * shortened the final part of the type inferencing and moved it to matrix creation in multiply --------- Co-authored-by: Jos de Jong * chore: update history * Fix: #3100 function `round` not handling round-off errors (#3136) * Fixing rounding bug from issue 3100 * Corrected syntax and converted if...else to logic using ternary operator * Removing nearlyEqual comparison because a false return value was mathematically impossible by user input. Adding dynamic epsilon logic to cover cases when a user requests to round a number to a higher precision than epsilon in the config file. Also adding tests to cover dynamic epsilon cases. * Removing dynamic epsilon and adding test for changing config.epsilon during runtime * Reintroducing nearly equal verification for round function. Adding test case for changing epsilon at runtime. Both tests for changing epsilon at runtime also verify the false nearlyEqual scenario. --------- Co-authored-by: Jos de Jong * chore: update history * chore: update devDependencies (most notably eslint) * chore: publish v12.4.0 * fix #3163: `toTex` wrongly returning `Infinity` for large BigNumbers * fix #3162: add license information about CSParse (#3164) * update history * fix: faster startup time of the CLI and REPL by loading the bundled file * feat: Interactive lorenz example (#3151) * Interactive lorenz * Separate Interactive Lorenz * Cleanup * Bigger graphs * Full screen examples --------- Co-authored-by: Jos de Jong * fix: give the inputsDiv a white background (see #3151) * chore: update history * chore: remove `polyfill.io` inside example (#3167) Co-authored-by: Jos de Jong * fix #3175: expose `math.Unit.ALIASES`, update history * chore: update history * doc: create CODE_OF_CONDUCT.md See #3174 * fix: #3172 simplify `"true and true"` * fix: #3175 cannot delete units using `math.Unit.deleteUnit` * chore: update devDependencies * chore: run `npm audit fix` * chore: publish v12.4.1 * docs: fix misleading documentation for expression tree traverse (#3177) Callback function for MathNode.traverse() returns void. Documentation says callback must return a replacement for the existing node (possibly copied from transform() above). * chore: update history * fix: #3180 fix type definitions of function `add` and `multiply` to allow more than two arguments * chore: update devDependencies (most notably `gulp@5`) * chore: replace utility function `values` with `Object.values` (fix #3194) * fix #3192: function `isNaN` returns `false` for `NaN` units in a matrix or array * Use referToSelf() to recursively check if various types are NaN in an array or matrix * fix array test description from isNegative to isNaN * Add test for units in a matrix --------- Co-authored-by: Jos de Jong * chore: update history * chore: update devDependencies * chore: publish `v12.4.2` * chore: replace util functions `values` and `contains` with using native JS functions (see #3194) * chore: replace util functions `values` and `contains` and usages of `indexOf` with using native JS functions `values` and `contains` (see #3194) * fix: serialization of Units without a value, see #1240 * Fix: outdated, incorrect documentation about the order of precedence for operator modulus `%`. See #3189 * feat: nearly equal with relative and absolute tolerance (#3152) * nearlyEqual with absolute and relative tolerances * Format * nearlyEqual for bigNumber * Added skip for NaN * Reduce diff a bit * Issue with examples in jsdcos * Updated all calls for nearlyEqual * Fixed failing tests * Changed epsilon to relTol, absTol * Changed references to epsilon in docs and tests * Added warning for config.epsilon * Fix warning in zeta.test * Added config test * Added sinon to test console.warn --------- Co-authored-by: Jos de Jong * chore: move `sinon` to devDependencies and fix two typos * chore: adjust `isPositive`, `isNegative`, and `isZero` to the new `relTol` and `absTol` * docs: document how to run tests for the type definitions * Improve quantileSeq typings (#3198) * Improve quantileSeq typings * Add tests, revert comment changes * Fix type tests * chore: update HISTORY.md * chore: cleanup entry files that are deprecated since `v8.0.0` (2020-11-06) * fix: upgrade to `fraction.js@4.3.7` * chore: convert CJS files to ESM (#3204) * chore: added test cases to deepForEach (#3211) * feat: implement support for `bigint` (#3207, #2737) * chore: move browserslist from package.json into `.browserslistrc` * chore: change browerslist to browsers that are not dead and fully support es6 * chore: improve browserslist to explicity require bigint support * chore: publish v12.4.3 * chore: update package-lock.json * chore: update devDependencies * chore: publish v13.0.0 * docs: document dropping JS engines that do not support E6 or bigint in v13 * fix: example advanced/custom_argument_parsing.js * chore: add unit tests for `deepMap`, `isCollection`, and `reduce` * docs: fix example `convert_fraction_to_bignumber.js` by upgrading to `typed-function@4.2.1` * Broadcast refactor (#3220) * chore: update history * fix: #3227 generated bundle containing `catch` blocks without parameters * fix: #2348 update type definitions of the `Parser` methods (#3226) Co-authored-by: Jos de Jong * chore: update devDependencies and run `npm audit fix` * chore: publish v13.0.1 * Further improve quantileSeq typings (#3223) Co-authored-by: Jos de Jong * chore: update history * chore: update devDependencies * fix #3227: change the minimum required JS version to ES2020 in the docs * chore: publish v13.0.2 * chore: update dependencies of the code editor example * fix: #3232 fix type definitions of function `format` to support notations `hex`, `bin`, and `oct` * fix: use exact values for US liquid volume units (#3229) 1 US gallon is defined as 231 cubic inches, which is exactly 3.785411784 L (since 1 inch is defined as 25.4 mm). Other units are defined against the gallon. Co-authored-by: Jos de Jong * fix: types static methods and members for Unit class (#3230) * fix: types static method for Unit class Changes unit interface to declare class to enable the adding of static methods. * refactor: change to not using declare class * fix: adds more unit static methods and updates tests * chore: moves test from wrong location * fix: adds additional static methods and updates jsDocs --------- Co-authored-by: Jos de Jong * chore: update history * chore: update devDependencies * chore: publish `v13.0.3` * chore: update package-lock.json * chore: revert updating devDependencies * chore: revert reverting updating devDependencies * chore: try use `ubuntu-24.04` instead of `ubuntu-latest` * chore: try use `ubuntu-22.04` instead of `ubuntu-24.04` * chore: try use `ubuntu-latest` instead of `ubuntu-22.04` again * chore: disable testing on Node 22 for now until we get mocha working again in GitHub actions * chore: publish `v13.0.3` for real * chore: enable testing on Node 22 again * feat: add matrix datatypes in more cases (#3235) * chore: update history * docs: add a link to the documentation page about the syntax expression from the function `evaluate` (fix #3238) * feat: export util functions for maps and improve documentation of `scope` (#3243) * feat: export util functions `isMap`, `isPartitionedMap`, and `isObjectWrappingMap` and improve the documentation of `scope` (see #3150) * chore: fix broken unit tests * docs: refine the explanation about scopes * chore: update history * fix: #3244 fix broken link to `ResultSet` in the docs about classes * fix: function `map` not always working with matrices (#3242) * Removed maxArgumentCount in favor of applyCallback * Making a pure _recurse function * Added cbrt tests, removed unnecesary changes in functions. * Fixed main bottleneck * Restored back function before unintended change * Fix format --------- Co-authored-by: Jos de Jong * chore: update history * chore: add tea.yaml file * docs: spelling fixes in the embedded docs (#3252) Co-authored-by: Jos de Jong * chore: update history * chore: add a benchmark testing `DenseMatrix.map(...)` and `DenseMatrix.forEach(...)` (see #3251) * feat: support multiple inputs in function `map` (#3228) * chore: update history * chore: update devDependencies * chore: publish `v13.1.0` * fix: various security vulnerabilities (#3255) * fix: disable parser functions in the CLI (security issue) * fix: ensure `ObjectWrappingMap` doesn't allow deleting unsafe properties (security issue) * fix: enable using methods and (safe) properties on plain arrays * docs: update the "Less vulnerable expression parser" section in the docs * chore: fix typos and linting issues * chore: keep functions like `simplify` enabled in the CLI * docs: update the security page * fix: ensure `ObjectWrappingMap.keys` cannot list unsafe properties * fix: when overwriting a rawArgs function with a non-rawArgs function it was still called with raw arguments * docs: fix a typo * chore: publish v13.1.1 * fix broken links in configuration.md (#3254) Co-authored-by: Jos de Jong * chore: update history * fix: improve the type definitions of `ConstantNode` to support all data types (#3257) * chore: update history * chore: fix broken benchmark * fix: #3259 function `symbolicEqual` missing in the TypeScript definitions * chore: update AUTHORS file * fix: #3259 revert the duplicate `symbolicEqual` definition and just export the existing definitions * fix: #3246 add type definitions for function `leafCount` * fix: #3253 cannot use identifiers containing special characters in function `derivative` * chore: update history * chore: extend the `map.js` benchmark * chore: fix linting issue * chore: improve performance of functions `map`, `filter` and `forEach` (#3256) * Implement reduceCallback * Add jsdocs * implement simplifyCallback in other functions * Moved recurse to array.js * Format * Separate transform callback * forEach transform * Renamed applyCallback to simplifyCallback * Simplified index transform * renamed to reducedCallback and simplifiedCallback to simpleCallback * chore: fix linting issue * Added forEach benchmark * renamed simplifyCallback to optimizeCallback --------- Co-authored-by: Jos de Jong * chore: update history * fix: #3267 implicit multiplication with a negative number and unit `in` * feat: speed up the `map()` and `forEach()` functions in DenseMatrix.js (#3251) * Optimize the map and forEach functions in DenseMatrix.js * Changed index back to Array from Uint32Array and clone it using index.slice(0) instead of [...index] * Fixed merge conflicts with the fast callback optimization * Fixed the documentation for _forEach() * Fixed _forEach comment and made it return an immutable index array * Resolved DenseMatrix unit test suggestions --------- Co-authored-by: Jos de Jong * chore: update HISTORY.md and AUTHORS * chore: use `codecov/codecov-action` * chore: try fix the codecov-action * chore: try fix the codecov-action * chore: try fix the codecov-action * chore: try fix the codecov-action * docs: document the syntax of `map` and `forEach` in the expression parser (#3272) * chore: update docs * chore: update devDependencies * chore: publish `v13.2.0` * chore: add a missing comma * docs: fix a typo on the Syntax page (#3276) * fix: update dependencies and devDependencies * chore: cleanup unused imports * chore: revert to `typescript@5.5.4` to keep the (old) eslint version happy --------- Co-authored-by: Glen Whitney Co-authored-by: Jos de Jong Co-authored-by: Vincent Tam Co-authored-by: Vrushaket Chaudhari <82214275+vrushaket@users.noreply.github.com> Co-authored-by: Juan Pablo Alvarado <63080419+juancodeaudio@users.noreply.github.com> Co-authored-by: Brooks Smith Co-authored-by: Alex Edgcomb Co-authored-by: Carl Osterwisch Co-authored-by: S.Y. Lee Co-authored-by: David Contreras Co-authored-by: David Contreras Co-authored-by: Hudsxn <143907857+Hudsxn@users.noreply.github.com> Co-authored-by: Rich Martinez <6185506+rich-martinez@users.noreply.github.com> Co-authored-by: Rich Martinez Co-authored-by: RandomGamingDev <83996185+RandomGamingDev@users.noreply.github.com> Co-authored-by: Brian Fugate Co-authored-by: Sukka Co-authored-by: Rohil Shah Co-authored-by: Laurent Gérin <41303636+lgerin@users.noreply.github.com> Co-authored-by: Adam Jones Co-authored-by: Lucas Eng Co-authored-by: Orel Ben Neriah <77707952+orelbn@users.noreply.github.com> Co-authored-by: Vistinum Co-authored-by: Vas Sudanagunta Co-authored-by: Brooks Smith <42363318+smith120bh@users.noreply.github.com> Co-authored-by: Jmar L. Pineda <63294460+Galm007@users.noreply.github.com> --- .babelrc | 1 + .browserslistrc | 4 + .eslintrc.cjs | 3 +- .github/workflows/browserstack.yaml | 6 +- .github/workflows/build.yaml | 31 +- .github/workflows/foresight.yaml | 52 - .github/workflows/local-browser.yaml | 6 +- .prettierrc.cjs | 1 + AUTHORS | 39 + CODE_OF_CONDUCT.md | 128 + HISTORY.md | 914 +- NOTICE | 2 +- README.md | 77 +- bin/cli.js | 38 +- bin/repl.js | 2 +- dist/math.js | 3 - dist/math.min.js | 3 - dist/package.json | 3 - docs/command_line_interface.md | 7 +- docs/core/configuration.md | 47 +- docs/datatypes/bigints.md | 54 + docs/datatypes/bignumbers.md | 11 +- docs/datatypes/fractions.md | 2 +- docs/datatypes/index.md | 3 + docs/datatypes/matrices.md | 135 +- docs/datatypes/numbers.md | 12 +- docs/datatypes/units.md | 63 +- docs/expressions/customization.md | 12 +- docs/expressions/expression_trees.md | 9 +- docs/expressions/parsing.md | 22 +- docs/expressions/security.md | 16 +- docs/expressions/syntax.md | 93 +- docs/index.md | 1 + docs/reference/classes.md | 4 +- .../advanced/convert_fraction_to_bignumber.js | 16 +- examples/advanced/custom_argument_parsing.js | 16 +- examples/advanced/custom_datatype.js | 3 +- .../custom_evaluate_using_factories.js | 5 +- .../advanced/custom_evaluate_using_import.js | 7 +- .../{custom_loading.mjs => custom_loading.js} | 6 +- .../advanced/custom_relational_functions.js | 2 +- examples/advanced/custom_scope_objects.js | 38 +- examples/advanced/expression_trees.js | 2 +- examples/advanced/function_transform.js | 2 +- examples/advanced/more_secure_eval.js | 2 +- examples/advanced/use_bigint.js | 43 - examples/algebra.js | 4 +- examples/basic_usage.js | 55 +- examples/bignumbers.js | 5 +- examples/browser/lorenz.html | 73 + examples/browser/lorenz_interactive.html | 193 + .../browser/pretty_printing_with_mathjax.html | 1 - .../rocket_trajectory_optimization.html | 11 +- examples/chaining.js | 26 +- examples/code editor/.gitignore | 24 + examples/code editor/README.md | 18 + examples/code editor/getExpressions.js | 59 + examples/code editor/index.html | 18 + examples/code editor/main.js | 214 + examples/code editor/mathjs-lang.js | 244 + examples/code editor/package-lock.json | 1120 + examples/code editor/package.json | 22 + examples/code editor/style.css | 60 + examples/complex_numbers.js | 4 +- examples/expressions.js | 106 +- examples/fractions.js | 4 +- examples/import.js | 4 +- examples/matrices.js | 52 +- examples/objects.js | 4 +- examples/package.json | 3 - examples/serialization.js | 4 +- examples/sparse_matrices.js | 4 +- examples/units.js | 64 +- gulpfile.cjs => gulpfile.js | 47 +- main/es5/index.js | 3 - main/es5/number.js | 3 - main/es5/package.json | 3 - main/esm/index.js | 3 - main/esm/number.js | 3 - main/esm/package.json | 3 - number.cjs | 3 - package-lock.json | 28261 +++++----------- package.json | 116 +- src/core/config.js | 12 +- src/core/create.js | 33 +- src/core/function/config.js | 38 +- src/core/function/import.js | 9 +- src/core/function/typed.js | 58 +- src/entry/configReadonly.js | 2 +- src/entry/typeChecks.js | 5 +- src/expression/Help.js | 23 +- src/expression/Parser.js | 2 +- .../embeddedDocs/construction/bigint.js | 17 + .../embeddedDocs/construction/bignumber.js | 2 +- .../embeddedDocs/construction/index.js | 5 +- .../embeddedDocs/construction/number.js | 2 +- src/expression/embeddedDocs/core/typed.js | 2 +- src/expression/embeddedDocs/embeddedDocs.js | 26 +- .../function/{matrix => algebra}/lyap.js | 4 +- .../function/algebra/polynomialRoot.js | 2 +- .../function/{matrix => algebra}/schur.js | 3 +- .../function/algebra/simplifyConstant.js | 2 +- .../function/{matrix => algebra}/sylvester.js | 5 +- .../embeddedDocs/function/arithmetic/hypot.js | 2 +- .../function/arithmetic/invmod.js | 6 +- .../embeddedDocs/function/arithmetic/pow.js | 4 +- .../embeddedDocs/function/arithmetic/round.js | 8 +- .../function/expression/evaluate.js | 9 +- .../embeddedDocs/function/matrix/diff.js | 21 +- .../embeddedDocs/function/matrix/eigs.js | 5 +- .../embeddedDocs/function/matrix/fft.js | 2 +- .../embeddedDocs/function/matrix/ifft.js | 2 +- .../embeddedDocs/function/matrix/kron.js | 2 +- .../embeddedDocs/function/matrix/map.js | 8 +- .../function/matrix/matrixFromColumns.js | 6 +- .../function/matrix/matrixFromFunction.js | 10 +- .../function/matrix/matrixFromRows.js | 6 +- .../function/matrix/partitionSelect.js | 7 +- .../embeddedDocs/function/matrix/range.js | 1 + .../embeddedDocs/function/matrix/rotate.js | 2 +- .../embeddedDocs/function/matrix/sort.js | 2 +- .../embeddedDocs/function/numeric/solveODE.js | 17 + .../function/probability/lgamma.js | 2 +- .../embeddedDocs/function/signal/freqz.js | 15 + .../embeddedDocs/function/signal/zpk2tf.js | 14 + .../embeddedDocs/function/special/zeta.js | 14 + .../embeddedDocs/function/statistics/corr.js | 22 + .../embeddedDocs/function/statistics/max.js | 2 +- .../embeddedDocs/function/statistics/mean.js | 2 +- .../embeddedDocs/function/statistics/min.js | 2 +- .../function/statistics/quantileSeq.js | 2 +- .../embeddedDocs/function/statistics/std.js | 4 +- .../embeddedDocs/function/statistics/sum.js | 3 +- .../function/statistics/variance.js | 4 +- .../function/trigonometry/acoth.js | 2 +- .../function/trigonometry/acsch.js | 2 +- .../embeddedDocs/function/utils/clone.js | 2 +- .../embeddedDocs/function/utils/numeric.js | 9 +- .../embeddedDocs/function/utils/print.js | 2 +- src/expression/function/evaluate.js | 5 + src/expression/function/parser.js | 2 +- src/expression/node/AccessorNode.js | 2 +- src/expression/node/ArrayNode.js | 2 +- src/expression/node/AssignmentNode.js | 4 +- src/expression/node/BlockNode.js | 2 +- src/expression/node/ConditionalNode.js | 2 +- src/expression/node/ConstantNode.js | 40 +- src/expression/node/FunctionAssignmentNode.js | 4 +- src/expression/node/FunctionNode.js | 38 +- src/expression/node/IndexNode.js | 2 +- src/expression/node/Node.js | 19 +- src/expression/node/ObjectNode.js | 14 +- src/expression/node/OperatorNode.js | 12 +- src/expression/node/ParenthesisNode.js | 2 +- src/expression/node/RangeNode.js | 2 +- src/expression/node/RelationalNode.js | 2 +- src/expression/node/SymbolNode.js | 4 +- src/expression/node/utils/assign.js | 10 +- src/expression/parse.js | 158 +- src/expression/transform/and.transform.js | 23 + src/expression/transform/bitAnd.transform.js | 28 + src/expression/transform/bitOr.transform.js | 31 + src/expression/transform/filter.transform.js | 78 +- src/expression/transform/forEach.transform.js | 68 +- src/expression/transform/index.transform.js | 12 +- src/expression/transform/map.transform.js | 78 +- src/expression/transform/or.transform.js | 23 + src/expression/transform/print.transform.js | 28 + .../transform/quantileSeq.transform.js | 33 + src/expression/transform/range.transform.js | 6 +- src/expression/transform/subset.transform.js | 6 +- .../utils/compileInlineExpression.js | 9 +- .../transform/utils/dimToZeroBase.js | 17 + .../transform/utils/lastDimToZeroBase.js | 10 +- .../transform/utils/transformCallback.js | 91 + src/factoriesAny.js | 13 + src/factoriesNumber.js | 5 +- src/function/algebra/decomposition/lup.js | 6 +- src/function/algebra/decomposition/qr.js | 10 +- src/function/algebra/derivative.js | 70 +- src/function/algebra/leafCount.js | 2 +- src/function/algebra/polynomialRoot.js | 2 +- src/function/algebra/rationalize.js | 12 +- src/function/algebra/resolve.js | 2 +- src/function/algebra/simplify.js | 39 +- src/function/algebra/simplifyConstant.js | 28 +- src/function/algebra/simplifyCore.js | 7 +- src/function/algebra/solver/lsolve.js | 8 +- src/function/algebra/solver/lsolveAll.js | 12 +- src/function/algebra/solver/usolve.js | 8 +- src/function/algebra/solver/usolveAll.js | 12 +- src/function/algebra/sparse/README.md | 12 + src/function/algebra/sparse/csAmd.js | 5 +- src/function/algebra/sparse/csChol.js | 5 +- src/function/algebra/sparse/csCounts.js | 5 +- src/function/algebra/sparse/csCumsum.js | 6 +- src/function/algebra/sparse/csDfs.js | 5 +- src/function/algebra/sparse/csEreach.js | 5 +- src/function/algebra/sparse/csEtree.js | 6 +- src/function/algebra/sparse/csFkeep.js | 6 +- src/function/algebra/sparse/csFlip.js | 6 +- src/function/algebra/sparse/csIpvec.js | 4 + src/function/algebra/sparse/csLeaf.js | 6 +- src/function/algebra/sparse/csLu.js | 6 +- src/function/algebra/sparse/csMark.js | 6 +- src/function/algebra/sparse/csMarked.js | 6 +- src/function/algebra/sparse/csPermute.js | 6 +- src/function/algebra/sparse/csPost.js | 5 +- src/function/algebra/sparse/csReach.js | 6 +- src/function/algebra/sparse/csSpsolve.js | 5 +- src/function/algebra/sparse/csSqr.js | 5 +- src/function/algebra/sparse/csSymperm.js | 5 +- src/function/algebra/sparse/csTdfs.js | 6 +- src/function/algebra/sparse/csUnflip.js | 5 +- src/function/algebra/symbolicEqual.js | 16 +- src/function/arithmetic/abs.js | 6 +- src/function/arithmetic/add.js | 63 +- src/function/arithmetic/addScalar.js | 10 +- src/function/arithmetic/ceil.js | 8 +- src/function/arithmetic/cube.js | 8 +- src/function/arithmetic/divide.js | 6 +- src/function/arithmetic/divideScalar.js | 10 +- src/function/arithmetic/dotDivide.js | 7 +- src/function/arithmetic/dotMultiply.js | 7 +- src/function/arithmetic/dotPow.js | 7 +- src/function/arithmetic/expm1.js | 2 +- src/function/arithmetic/floor.js | 8 +- src/function/arithmetic/gcd.js | 81 +- src/function/arithmetic/hypot.js | 6 +- src/function/arithmetic/lcm.js | 7 +- src/function/arithmetic/mod.js | 60 +- src/function/arithmetic/multiply.js | 66 +- src/function/arithmetic/multiplyScalar.js | 10 +- src/function/arithmetic/nthRoot.js | 7 +- src/function/arithmetic/nthRoots.js | 3 +- src/function/arithmetic/pow.js | 8 +- src/function/arithmetic/round.js | 104 +- src/function/arithmetic/sign.js | 8 +- src/function/arithmetic/square.js | 8 +- src/function/arithmetic/subtract.js | 45 +- src/function/arithmetic/subtractScalar.js | 56 + src/function/arithmetic/unaryMinus.js | 6 +- src/function/arithmetic/unaryPlus.js | 22 +- src/function/bitwise/bitAnd.js | 16 +- src/function/bitwise/bitNot.js | 5 +- src/function/bitwise/bitOr.js | 16 +- src/function/bitwise/bitXor.js | 16 +- src/function/bitwise/leftShift.js | 15 +- src/function/bitwise/rightArithShift.js | 15 +- src/function/bitwise/rightLogShift.js | 7 +- src/function/combinatorics/stirlingS2.js | 4 +- src/function/geometry/distance.js | 69 +- src/function/geometry/intersect.js | 2 +- src/function/logical/and.js | 13 +- src/function/logical/not.js | 4 +- src/function/logical/or.js | 13 +- src/function/logical/xor.js | 13 +- src/function/matrix/apply.js | 2 +- src/function/matrix/column.js | 6 +- src/function/matrix/concat.js | 32 +- src/function/matrix/det.js | 14 +- src/function/matrix/diff.js | 6 +- src/function/matrix/dot.js | 6 +- src/function/matrix/eigs.js | 143 +- src/function/matrix/eigs/complexEigs.js | 127 +- .../{realSymetric.js => realSymmetric.js} | 110 +- src/function/matrix/fft.js | 58 +- src/function/matrix/filter.js | 18 +- src/function/matrix/flatten.js | 10 +- src/function/matrix/forEach.js | 28 +- src/function/matrix/getMatrixDataType.js | 2 +- src/function/matrix/ifft.js | 4 +- src/function/matrix/kron.js | 8 +- src/function/matrix/map.js | 166 +- src/function/matrix/partitionSelect.js | 9 +- src/function/matrix/range.js | 159 +- src/function/matrix/row.js | 6 +- src/function/matrix/size.js | 14 +- src/function/matrix/sqrtm.js | 2 +- src/function/matrix/squeeze.js | 6 +- src/function/matrix/subset.js | 107 +- src/function/numeric/solveODE.js | 322 + src/function/probability/pickRandom.js | 4 +- src/function/probability/random.js | 2 +- src/function/probability/randomInt.js | 2 +- src/function/relational/compare.js | 23 +- src/function/relational/compareNatural.js | 2 +- src/function/relational/compareText.js | 7 +- src/function/relational/equal.js | 13 +- src/function/relational/equalScalar.js | 16 +- src/function/relational/larger.js | 19 +- src/function/relational/largerEq.js | 21 +- src/function/relational/smaller.js | 19 +- src/function/relational/smallerEq.js | 19 +- src/function/relational/unequal.js | 9 +- src/function/set/setIsSubset.js | 2 +- src/function/set/setSize.js | 5 +- src/function/signal/freqz.js | 109 + src/function/signal/zpk2tf.js | 86 + src/function/special/erf.js | 3 + src/function/special/zeta.js | 142 + src/function/statistics/corr.js | 75 + src/function/statistics/cumsum.js | 4 +- src/function/statistics/mad.js | 2 +- src/function/statistics/max.js | 9 +- src/function/statistics/mean.js | 4 +- src/function/statistics/min.js | 7 +- src/function/statistics/mode.js | 2 +- src/function/statistics/prod.js | 5 +- src/function/statistics/quantileSeq.js | 259 +- src/function/statistics/std.js | 2 +- src/function/statistics/sum.js | 8 +- .../statistics/utils/improveErrorMessage.js | 4 +- src/function/statistics/variance.js | 2 +- src/function/string/bin.js | 6 +- src/function/string/format.js | 6 +- src/function/string/hex.js | 6 +- src/function/string/oct.js | 6 +- src/function/string/print.js | 6 +- src/function/trigonometry/acoth.js | 4 +- src/function/trigonometry/acsch.js | 4 +- src/function/trigonometry/atan2.js | 7 +- src/function/unit/to.js | 13 +- src/function/utils/hasNumericValue.js | 4 +- src/function/utils/isInteger.js | 6 +- src/function/utils/isNaN.js | 10 +- src/function/utils/isNegative.js | 22 +- src/function/utils/isNumeric.js | 5 +- src/function/utils/isPositive.js | 23 +- src/function/utils/isPrime.js | 21 +- src/function/utils/isZero.js | 21 +- src/function/utils/numeric.js | 10 +- src/function/utils/typeOf.js | 1 + src/header.js | 2 +- src/json/replacer.js | 7 + src/plain/number/arithmetic.js | 15 +- src/plain/number/constants.js | 1 - src/type/bigint.js | 72 + src/type/bignumber/function/bignumber.js | 14 +- src/type/fraction/function/fraction.js | 12 +- src/type/matrix/DenseMatrix.js | 161 +- src/type/matrix/MatrixIndex.js | 46 +- src/type/matrix/SparseMatrix.js | 20 +- src/type/matrix/function/index.js | 10 +- src/type/matrix/utils/broadcast.js | 40 + src/type/matrix/utils/matAlgo01xDSid.js | 8 +- src/type/matrix/utils/matAlgo02xDS0.js | 8 +- src/type/matrix/utils/matAlgo03xDSf.js | 8 +- src/type/matrix/utils/matAlgo04xSidSid.js | 8 +- src/type/matrix/utils/matAlgo05xSfSf.js | 8 +- src/type/matrix/utils/matAlgo06xS0S0.js | 8 +- src/type/matrix/utils/matAlgo07xSSf.js | 8 +- src/type/matrix/utils/matAlgo08xS0Sid.js | 8 +- src/type/matrix/utils/matAlgo09xS0Sf.js | 8 +- src/type/matrix/utils/matrixAlgorithmSuite.js | 37 +- src/type/number.js | 18 +- src/type/unit/Unit.js | 243 +- src/type/unit/function/splitUnit.js | 2 +- src/type/unit/physicalConstants.js | 2 +- src/utils/array.js | 286 +- src/utils/bignumber/formatter.js | 52 +- src/utils/bignumber/nearlyEqual.js | 56 +- src/utils/collection.js | 2 +- src/utils/complex.js | 15 +- src/utils/customs.js | 27 +- src/utils/factory.js | 3 +- src/utils/function.js | 14 - src/utils/is.js | 38 + src/utils/latex.js | 4 + src/utils/lruQueue.js | 4 +- src/utils/map.js | 157 +- src/utils/noop.js | 1 - src/utils/number.js | 198 +- src/utils/object.js | 17 +- src/utils/optimizeCallback.js | 77 + src/utils/print.js | 1 + src/utils/scope.js | 18 +- src/utils/snapshot.js | 9 +- src/utils/string.js | 32 +- src/version.js | 2 +- tea.yaml | 6 + test/benchmark/algebra.js | 14 +- test/benchmark/expression_parser.js | 12 +- test/benchmark/factorial.js | 6 +- test/benchmark/forEach.js | 55 + test/benchmark/index.js | 15 +- test/benchmark/load.js | 9 +- test/benchmark/map.js | 55 + test/benchmark/matrix_operations.js | 24 +- test/benchmark/package.json | 3 - test/benchmark/prime.js | 8 +- test/benchmark/roots.js | 8 +- test/benchmark/scope_variables.js | 20 + test/benchmark/unit_parser.js | 8 +- test/browser-test-config/base-karma.js | 1 - .../entry/mainAny.test.js | 2 +- .../{browser.test.js => browser.test.cjs} | 6 +- .../cli/{cli.test.js => cli.test.cjs} | 0 .../{commonjs.test.js => commonjs.test.cjs} | 1 + ...tance.test.js => defaultInstance.test.cjs} | 12 +- test/node-tests/doc.test.js | 90 +- test/node-tests/esm.test.js | 13 +- test/node-tests/{esmApp.mjs => esmApp.js} | 0 ...mAppNumberOnly.mjs => esmAppNumberOnly.js} | 0 .../alegbra/decomposition/slu.test.js | 24 +- .../function/alegbra/sparse/csAmd.test.js | 27 +- .../function/alegbra/sparse/csLu.test.js | 31 +- .../function/arithmetic/multiply.test.js | 8 +- test/node-tests/package.json | 3 - test/node-tests/pollutedObjectPrototype.js | 7 +- .../treeShaking/treeShaking.test.js | 19 +- .../{treeShakingApp.mjs => treeShakingApp.js} | 0 test/typescript-tests/testTypes.ts | 560 +- test/unit-tests/approx.test.js | 102 +- test/unit-tests/constants.test.js | 28 +- test/unit-tests/core/config.test.js | 20 + test/unit-tests/core/import.test.js | 4 +- test/unit-tests/core/typed.test.js | 71 +- test/unit-tests/expression/Parser.test.js | 4 +- .../expression/function/evaluate.test.js | 4 +- .../expression/function/help.test.js | 7 + .../expression/node/AccessorNode.test.js | 24 + .../expression/node/ArrayNode.test.js | 24 + .../expression/node/AssignmentNode.test.js | 25 +- .../expression/node/BlockNode.test.js | 25 +- .../expression/node/ConditionalNode.test.js | 23 +- .../expression/node/ConstantNode.test.js | 27 +- .../node/FunctionAssignmentNode.test.js | 29 +- .../expression/node/FunctionNode.test.js | 33 +- .../expression/node/IndexNode.test.js | 20 + .../expression/node/ObjectNode.test.js | 14 + .../expression/node/OperatorNode.test.js | 13 + .../expression/node/ParenthesisNode.test.js | 13 + .../expression/node/RangeNode.test.js | 21 + .../expression/node/RelationalNode.test.js | 24 + .../expression/node/SymbolNode.test.js | 15 +- test/unit-tests/expression/parse.test.js | 404 +- test/unit-tests/expression/security.test.js | 10 + .../transform/std.transform.test.js | 6 +- .../transform/variance.transform.test.js | 6 +- .../algebra/decomposition/lup.test.js | 52 +- .../function/algebra/decomposition/qr.test.js | 28 +- .../algebra/decomposition/schur.test.js | 1 + .../algebra/decomposition/slu.test.js | 10 +- .../function/algebra/derivative.test.js | 46 +- test/unit-tests/function/algebra/lyap.test.js | 1 + .../function/algebra/polynomialRoot.test.js | 45 +- .../function/algebra/simplify.test.js | 11 + .../function/algebra/simplifyCore.test.js | 9 + .../function/algebra/solver/lsolve.test.js | 14 +- .../function/algebra/solver/lsolveAll.test.js | 26 +- .../function/algebra/solver/lusolve.test.js | 48 +- .../function/algebra/solver/usolve.test.js | 14 +- .../function/algebra/solver/usolveAll.test.js | 26 +- .../function/algebra/sparse/csLu.test.js | 12 +- .../function/algebra/sylvester.test.js | 1 + .../function/arithmetic/abs.test.js | 9 + .../function/arithmetic/add.test.js | 9 + .../function/arithmetic/addScalar.test.js | 39 +- .../function/arithmetic/cbrt.test.js | 22 +- .../function/arithmetic/ceil.test.js | 82 +- .../function/arithmetic/createHypot.test.js | 4 +- .../function/arithmetic/cube.test.js | 6 + .../function/arithmetic/divide.test.js | 89 +- .../function/arithmetic/dotDivide.test.js | 39 +- .../function/arithmetic/dotMultiply.test.js | 122 +- .../function/arithmetic/dotPow.test.js | 153 +- .../function/arithmetic/exp.test.js | 60 +- .../function/arithmetic/expm1.test.js | 60 +- .../function/arithmetic/gcd.test.js | 34 + .../function/arithmetic/lcm.test.js | 5 + .../function/arithmetic/log.test.js | 54 +- .../function/arithmetic/log10.test.js | 58 +- .../function/arithmetic/log1p.test.js | 50 +- .../function/arithmetic/log2.test.js | 40 +- .../function/arithmetic/mod.test.js | 87 +- .../function/arithmetic/multiply.test.js | 212 +- .../function/arithmetic/nthRoot.test.js | 79 +- .../function/arithmetic/nthRoots.test.js | 5 +- .../function/arithmetic/pow.test.js | 170 +- .../function/arithmetic/round.test.js | 79 +- .../function/arithmetic/sign.test.js | 12 +- .../function/arithmetic/square.test.js | 6 + .../function/arithmetic/subtract.test.js | 17 +- .../arithmetic/subtractScalar.test.js | 178 + .../function/arithmetic/unaryMinus.test.js | 6 + .../function/arithmetic/unaryPlus.test.js | 19 +- .../function/bitwise/bitAnd.test.js | 18 + .../function/bitwise/bitNot.test.js | 6 + .../unit-tests/function/bitwise/bitOr.test.js | 21 + .../function/bitwise/bitXor.test.js | 18 + .../function/bitwise/leftShift.test.js | 21 + .../function/bitwise/rightArithShift.test.js | 22 + .../function/bitwise/rightLogShift.test.js | 5 + test/unit-tests/function/complex/arg.test.js | 4 +- test/unit-tests/function/complex/conj.test.js | 1 + .../function/geometry/distance.test.js | 23 +- test/unit-tests/function/logical/and.test.js | 21 + test/unit-tests/function/logical/not.test.js | 6 + test/unit-tests/function/logical/or.test.js | 17 + test/unit-tests/function/logical/xor.test.js | 18 + test/unit-tests/function/matrix/apply.test.js | 1 + .../unit-tests/function/matrix/column.test.js | 10 + test/unit-tests/function/matrix/det.test.js | 16 + test/unit-tests/function/matrix/diff.test.js | 8 +- test/unit-tests/function/matrix/eigs.test.js | 170 +- test/unit-tests/function/matrix/expm.test.js | 14 +- test/unit-tests/function/matrix/fft.test.js | 68 +- test/unit-tests/function/matrix/ifft.test.js | 12 +- test/unit-tests/function/matrix/inv.test.js | 14 +- test/unit-tests/function/matrix/kron.test.js | 14 +- test/unit-tests/function/matrix/map.test.js | 218 +- test/unit-tests/function/matrix/pinv.test.js | 13 +- test/unit-tests/function/matrix/range.test.js | 20 +- .../unit-tests/function/matrix/rotate.test.js | 10 +- .../function/matrix/rotationMatrix.test.js | 92 +- test/unit-tests/function/matrix/row.test.js | 10 + test/unit-tests/function/matrix/size.test.js | 28 +- test/unit-tests/function/matrix/sqrtm.test.js | 16 +- .../function/matrix/squeeze.test.js | 10 +- .../unit-tests/function/matrix/subset.test.js | 99 +- test/unit-tests/function/matrix/trace.test.js | 22 +- .../function/numeric/solveODE.test.js | 238 + .../function/probability/factorial.test.js | 6 +- .../function/probability/gamma.test.js | 76 +- .../function/probability/lgamma.test.js | 94 +- .../function/relational/compare.test.js | 33 +- .../relational/compareNatural.test.js | 4 +- .../function/relational/compareText.test.js | 4 + .../function/relational/equal.test.js | 23 +- .../function/relational/larger.test.js | 34 +- .../function/relational/largerEq.test.js | 31 +- .../function/relational/smaller.test.js | 31 +- .../function/relational/smallerEq.test.js | 32 +- .../function/relational/unequal.test.js | 24 +- test/unit-tests/function/signal/freqz.test.js | 86 + .../unit-tests/function/signal/zpk2tf.test.js | 48 + test/unit-tests/function/special/zeta.test.js | 94 + .../function/statistics/corr.test.js | 46 + .../function/statistics/max.test.js | 16 +- .../function/statistics/mean.test.js | 6 +- .../function/statistics/median.test.js | 10 +- .../function/statistics/min.test.js | 16 +- .../function/statistics/prod.test.js | 20 +- .../function/statistics/quantileSeq.test.js | 79 +- .../function/statistics/std.test.js | 10 +- .../function/statistics/sum.test.js | 20 +- .../function/statistics/variance.test.js | 6 +- .../unit-tests/function/string/format.test.js | 93 + test/unit-tests/function/string/print.test.js | 23 + .../function/trigonometry/acos.test.js | 48 +- .../function/trigonometry/acosh.test.js | 44 +- .../function/trigonometry/acot.test.js | 38 +- .../function/trigonometry/acoth.test.js | 42 +- .../function/trigonometry/acsc.test.js | 48 +- .../function/trigonometry/acsch.test.js | 42 +- .../function/trigonometry/asec.test.js | 48 +- .../function/trigonometry/asech.test.js | 42 +- .../function/trigonometry/asin.test.js | 48 +- .../function/trigonometry/asinh.test.js | 44 +- .../function/trigonometry/atan.test.js | 46 +- .../function/trigonometry/atan2.test.js | 11 +- .../function/trigonometry/atanh.test.js | 42 +- .../function/trigonometry/cos.test.js | 58 +- .../function/trigonometry/cosh.test.js | 26 +- .../function/trigonometry/cot.test.js | 52 +- .../function/trigonometry/coth.test.js | 26 +- .../function/trigonometry/csc.test.js | 54 +- .../function/trigonometry/csch.test.js | 30 +- .../function/trigonometry/sec.test.js | 68 +- .../function/trigonometry/sech.test.js | 26 +- .../function/trigonometry/sin.test.js | 56 +- .../function/trigonometry/sinh.test.js | 28 +- .../function/trigonometry/tan.test.js | 48 +- .../function/trigonometry/tanh.test.js | 26 +- test/unit-tests/function/unit/to.test.js | 32 +- test/unit-tests/function/utils/clone.test.js | 8 + .../function/utils/hasNumericValue.test.js | 3 + .../function/utils/isInteger.test.js | 6 + test/unit-tests/function/utils/isNaN.test.js | 14 +- .../function/utils/isNegative.test.js | 14 + .../function/utils/isNumeric.test.js | 3 + .../function/utils/isPositive.test.js | 14 + .../unit-tests/function/utils/isPrime.test.js | 15 + test/unit-tests/function/utils/isZero.test.js | 15 + test/unit-tests/function/utils/typeof.test.js | 5 + test/unit-tests/json/replacer.test.js | 21 + test/unit-tests/json/reviver.test.js | 26 + .../plain/number/arithmetic.test.js | 27 + test/unit-tests/type/bigint.test.js | 81 + .../type/bignumber/function/bignumber.test.js | 18 + test/unit-tests/type/chain/Chain.test.js | 2 +- .../type/fraction/function/fraction.test.js | 18 + .../type/matrix/DenseMatrix.test.js | 49 +- .../type/matrix/function/matrix.test.js | 12 +- .../type/matrix/utils/broadcast.test.js | 76 + .../type/matrix/utils/deepForEach.test.js | 64 +- .../type/matrix/utils/deepMap.test.js | 69 +- .../matrix/utils/getMatrixDataType.test.js | 20 + .../type/matrix/utils/isCollection.test.js | 65 +- .../type/matrix/utils/reduce.test.js | 62 +- test/unit-tests/type/number.test.js | 57 +- test/unit-tests/type/numeric.test.js | 8 +- test/unit-tests/type/unit/Unit.test.js | 118 +- .../type/unit/physicalConstants.test.js | 14 +- test/unit-tests/utils/array.test.js | 160 +- .../utils/bignumber/nearlyEqual.test.js | 114 +- test/unit-tests/utils/customs.test.js | 64 +- test/unit-tests/utils/function.test.js | 39 +- test/unit-tests/utils/is.test.js | 11 +- test/unit-tests/utils/map.test.js | 294 +- test/unit-tests/utils/number.test.js | 116 +- test/unit-tests/utils/object.test.js | 7 +- test/unit-tests/utils/string.test.js | 15 + tools/approx.js | 33 +- tools/docgenerator.js | 55 +- tools/entryGenerator.js | 40 +- tools/matrixmarket.js | 27 +- tools/package.json | 3 - tools/update-authors.js | 12 +- tools/utils.js | 4 +- tools/validateAsciiChars.js | 8 +- tools/whitelistgenerator.js | 5 +- tsconfig.json | 10 +- types/EXPLANATION.md | 66 + types/index.d.ts | 13599 ++++---- 626 files changed, 29764 insertions(+), 32935 deletions(-) create mode 100644 .browserslistrc delete mode 100644 .github/workflows/foresight.yaml create mode 100644 CODE_OF_CONDUCT.md delete mode 100644 dist/math.js delete mode 100644 dist/math.min.js delete mode 100644 dist/package.json create mode 100644 docs/datatypes/bigints.md rename examples/advanced/{custom_loading.mjs => custom_loading.js} (95%) delete mode 100644 examples/advanced/use_bigint.js create mode 100644 examples/browser/lorenz.html create mode 100644 examples/browser/lorenz_interactive.html create mode 100644 examples/code editor/.gitignore create mode 100644 examples/code editor/README.md create mode 100644 examples/code editor/getExpressions.js create mode 100644 examples/code editor/index.html create mode 100644 examples/code editor/main.js create mode 100644 examples/code editor/mathjs-lang.js create mode 100644 examples/code editor/package-lock.json create mode 100644 examples/code editor/package.json create mode 100644 examples/code editor/style.css delete mode 100644 examples/package.json rename gulpfile.cjs => gulpfile.js (85%) delete mode 100644 main/es5/index.js delete mode 100644 main/es5/number.js delete mode 100644 main/es5/package.json delete mode 100644 main/esm/index.js delete mode 100644 main/esm/number.js delete mode 100644 main/esm/package.json delete mode 100644 number.cjs create mode 100644 src/expression/embeddedDocs/construction/bigint.js rename src/expression/embeddedDocs/function/{matrix => algebra}/lyap.js (77%) rename src/expression/embeddedDocs/function/{matrix => algebra}/schur.js (83%) rename src/expression/embeddedDocs/function/{matrix => algebra}/sylvester.js (70%) create mode 100644 src/expression/embeddedDocs/function/numeric/solveODE.js create mode 100644 src/expression/embeddedDocs/function/signal/freqz.js create mode 100644 src/expression/embeddedDocs/function/signal/zpk2tf.js create mode 100644 src/expression/embeddedDocs/function/special/zeta.js create mode 100644 src/expression/embeddedDocs/function/statistics/corr.js create mode 100644 src/expression/transform/and.transform.js create mode 100644 src/expression/transform/bitAnd.transform.js create mode 100644 src/expression/transform/bitOr.transform.js create mode 100644 src/expression/transform/or.transform.js create mode 100644 src/expression/transform/print.transform.js create mode 100644 src/expression/transform/quantileSeq.transform.js create mode 100644 src/expression/transform/utils/dimToZeroBase.js create mode 100644 src/expression/transform/utils/transformCallback.js create mode 100644 src/function/algebra/sparse/README.md create mode 100644 src/function/arithmetic/subtractScalar.js rename src/function/matrix/eigs/{realSymetric.js => realSymmetric.js} (76%) create mode 100644 src/function/numeric/solveODE.js create mode 100644 src/function/signal/freqz.js create mode 100644 src/function/signal/zpk2tf.js create mode 100644 src/function/special/zeta.js create mode 100644 src/function/statistics/corr.js create mode 100644 src/type/bigint.js create mode 100644 src/type/matrix/utils/broadcast.js create mode 100644 src/utils/optimizeCallback.js create mode 100644 src/utils/print.js create mode 100644 tea.yaml create mode 100644 test/benchmark/forEach.js create mode 100644 test/benchmark/map.js delete mode 100644 test/benchmark/package.json create mode 100644 test/benchmark/scope_variables.js rename test/node-tests/{browser.test.js => browser.test.cjs} (96%) rename test/node-tests/cli/{cli.test.js => cli.test.cjs} (100%) rename test/node-tests/{commonjs.test.js => commonjs.test.cjs} (99%) rename test/node-tests/{defaultInstance.test.js => defaultInstance.test.cjs} (96%) rename test/node-tests/{esmApp.mjs => esmApp.js} (100%) rename test/node-tests/{esmAppNumberOnly.mjs => esmAppNumberOnly.js} (100%) delete mode 100644 test/node-tests/package.json rename test/node-tests/treeShaking/{treeShakingApp.mjs => treeShakingApp.js} (100%) create mode 100644 test/unit-tests/function/arithmetic/subtractScalar.test.js create mode 100644 test/unit-tests/function/numeric/solveODE.test.js create mode 100644 test/unit-tests/function/signal/freqz.test.js create mode 100644 test/unit-tests/function/signal/zpk2tf.test.js create mode 100644 test/unit-tests/function/special/zeta.test.js create mode 100644 test/unit-tests/function/statistics/corr.test.js create mode 100644 test/unit-tests/plain/number/arithmetic.test.js create mode 100644 test/unit-tests/type/bigint.test.js create mode 100644 test/unit-tests/type/matrix/utils/broadcast.test.js delete mode 100644 tools/package.json create mode 100644 types/EXPLANATION.md diff --git a/.babelrc b/.babelrc index 66bda36476..8684d1bf4f 100644 --- a/.babelrc +++ b/.babelrc @@ -4,6 +4,7 @@ ], "plugins": [ "@babel/plugin-transform-object-assign", + "@babel/plugin-transform-optional-catch-binding", "@babel/plugin-transform-runtime" ], "ignore": [ diff --git a/.browserslistrc b/.browserslistrc new file mode 100644 index 0000000000..6644b184bc --- /dev/null +++ b/.browserslistrc @@ -0,0 +1,4 @@ +# Test out at: https://browsersl.ist/ + +fully supports es6 and fully supports bigint +not dead diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 2131022afe..fb66ab5c16 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -2,7 +2,8 @@ module.exports = { env: { browser: true, es2021: true, - node: true + node: true, + mocha: true }, extends: ['eslint:recommended'], parserOptions: { diff --git a/.github/workflows/browserstack.yaml b/.github/workflows/browserstack.yaml index 507665bb84..086a41d392 100644 --- a/.github/workflows/browserstack.yaml +++ b/.github/workflows/browserstack.yaml @@ -11,10 +11,10 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: - node-version: 16.x + node-version: 20.x - run: npm ci - run: npm run test:browserstack env: diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 0f68d61b70..6d10c4a406 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -13,12 +13,12 @@ jobs: strategy: matrix: - node-version: [14.x, 16.x] + node-version: [18.x, 20.x, 22.x] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} - run: npm ci @@ -30,10 +30,10 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: - node-version: 16.x + node-version: 20.x - run: npm ci - run: npm run lint env: @@ -43,23 +43,28 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: - node-version: 16.x + node-version: 20.x - run: npm ci - - run: npm run coverage && npx codecov + - run: npm run coverage env: CI: true + - name: Upload coverage reports to Codecov + uses: codecov/codecov-action@v4 + with: + token: ${{ secrets.CODECOV_TOKEN }} + fail_ci_if_error: true build-and-test: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: - node-version: 16.x + node-version: 20.x - run: npm ci - run: npm run build-and-test env: diff --git a/.github/workflows/foresight.yaml b/.github/workflows/foresight.yaml deleted file mode 100644 index 7fa39b0152..0000000000 --- a/.github/workflows/foresight.yaml +++ /dev/null @@ -1,52 +0,0 @@ -# This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node -# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions - -name: Foresight CI Workflow - - -on: - push: - branches: [ "main", "develop" ] - pull_request: - branches: [ "main", "develop" ] - workflow_dispatch: - -jobs: - build: - - runs-on: ubuntu-latest - - strategy: - matrix: - node-version: [14.x, 16.x] - # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ - - steps: - - uses: actions/checkout@v3 - - - name: Collect Workflow Telemetry - if: always() - uses: runforesight/foresight-workflow-kit-action@v1 - with: - api_key: ${{ secrets.FORESIGHT_API_KEY }} - - - - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v3 - with: - node-version: ${{ matrix.node-version }} - cache: 'npm' - - - run: npm ci - - run: npm run test:src -- --reporter mocha-junit-reporter --reporter-options mochaFile=./test-results.xml - env: - CI: true - - - name: Analyze Test and/or Coverage Results - if: always() - uses: runforesight/foresight-test-kit-action@v1 - with: - api_key: ${{ secrets.FORESIGHT_API_KEY }} - test_framework: JEST - test_format: JUNIT - test_path: ./test-results.xml diff --git a/.github/workflows/local-browser.yaml b/.github/workflows/local-browser.yaml index faae35580e..91a942b247 100644 --- a/.github/workflows/local-browser.yaml +++ b/.github/workflows/local-browser.yaml @@ -8,10 +8,10 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: - node-version: 16.x + node-version: 20.x - run: npm ci - run: npm run test:browser env: diff --git a/.prettierrc.cjs b/.prettierrc.cjs index 35fcafaf2e..2c815ce252 100644 --- a/.prettierrc.cjs +++ b/.prettierrc.cjs @@ -1,4 +1,5 @@ module.exports = { semi: false, singleQuote: true, + trailingComma: 'none' } diff --git a/AUTHORS b/AUTHORS index 8c8586312f..2e52a93b14 100644 --- a/AUTHORS +++ b/AUTHORS @@ -214,5 +214,44 @@ Henry Chan brunoSnoww <101579047+brunoSnoww@users.noreply.github.com> Evan Miller Evan Miller +Timur <35872220+bornova@users.noreply.github.com> +Ari Markowitz +Jay Wang +Jaeu Jeong +cyavictor88 <100557319+cyavictor88@users.noreply.github.com> +David Contreras +Jakub Riegel +Angus Comrie +TMTron +Maxim Mazurok +kunalagrwl +Michael Greminger +Kiku +MaybePixem <47889538+MaybePixem@users.noreply.github.com> +Aly Khaled +BuildTools +Anik Patel <74193405+Bobingstern@users.noreply.github.com> +Vrushaket Chaudhari <82214275+vrushaket@users.noreply.github.com> +Praise Nnamonu <110940850+praisennamonu1@users.noreply.github.com> +Vincent Tam +Juan Pablo Alvarado <63080419+juancodeaudio@users.noreply.github.com> +Brooks Smith +Alex Edgcomb +S.Y. Lee +Hudsxn <143907857+Hudsxn@users.noreply.github.com> +Rich Martinez <6185506+rich-martinez@users.noreply.github.com> +Rich Martinez +RandomGamingDev <83996185+RandomGamingDev@users.noreply.github.com> +Brian Fugate +Sukka +Rohil Shah +Laurent Gérin <41303636+lgerin@users.noreply.github.com> +Adam Jones +Lucas Eng +Orel Ben Neriah <77707952+orelbn@users.noreply.github.com> +Vistinum +Vas Sudanagunta +Brooks Smith <42363318+smith120bh@users.noreply.github.com> +Jmar L. Pineda <63294460+Galm007@users.noreply.github.com> # Generated by tools/update-authors.js diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..73fd2cfdd0 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +mathjs. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/HISTORY.md b/HISTORY.md index 3cd9fc23e5..1ebe957729 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,16 +1,394 @@ # History -# unpublished changes since 11.5.0 +# unpublished changes since 13.2.0 + +- Update to the latest version of `complex.js`. + +# 2024-10-02, 13.2.0 + +- Feat: improve performance of functions `map`, `filter` and `forEach` (#3256). + Thanks @dvd101x. +- Feat: improve performance of the methods `map()` and `forEach()` + of `DenseMatrix` (#3251). Thanks @Galm007. +- Fix: #3253 cannot use identifiers containing special characters in function + `derivative`. +- Fix: improve the type definitions of `ConstantNode` to support all data + types (#3257). Thanks @smith120bh. +- Fix: #3259 function `symbolicEqual` missing in the TypeScript definitions. +- Fix: #3246 function `leafCount` missing in the TypeScript definitions. +- Fix: #3267 implicit multiplication with a negative number and unit `in`. +- Docs: fix broken links on the Configuration page. Thanks @vassudanagunta. +- Docs: document the syntax of `map` and `forEach` in the expression parser + (#3272). Thanks @dvd101x. + +# 2024-08-27, 13.1.1 + +- Fix security vulnerability in the CLI and web API allowing to call functions + `import`, `createUnit` and `reviver`, allowing to get access to the internal + math namespace and allowing arbitrary code execution. Thanks @StarlightPWN. +- Fix security vulnerability: when overwriting a `rawArgs` function with a + non-`rawArgs` function, it was still called with raw arguments. This was both + a functional issue and a security issue. Thanks @StarlightPWN. +- Fix security vulnerability: ensure that `ObjectWrappingMap` cannot delete + unsafe properties. Thanks @StarlightPWN. +- Fix: not being able to use methods and properties on arrays inside the + expression parser. + +# 2024-08-26, 13.1.0 + +- Feat: support multiple inputs in function `map` (#3228, #3196). + Thanks @dvd101x. +- Feat: add matrix datatypes in more cases (#3235). Thanks @dvd101x. +- Feat: export util functions `isMap`, `isPartitionedMap`, and + `isObjectWrappingMap`. +- Fix: #3241 function `map` not always working with matrices (#3242). + Thanks @dvd101x. +- Fix: #3244 fix broken link to `ResultSet` in the docs about classes. +- Docs: add a link to the documentation page about the syntax expression + from the function `evaluate` (see #3238). +- Docs: improve the documentation of `scope` and fix the example + `custom_scope_objects.js` (#3150) +- Docs: spelling fixes in the embedded docs (#3252). Thanks @dvd101x. + +# 2024-07-19, 13.0.3 + +- Fix: #3232 fix type definitions of function `format` to support notations + `hex`, `bin`, and `oct`. +- Fix: use more precise definitions for US liquid volume units (#3229). + Thanks @Vistinum. +- Fix: #2286 types static methods and members for Unit class (#3230). + Thanks @orelbn. + +# 2024-07-04, 13.0.2 + +- Fix an error in the type definitions of `quantileSeq` (#3223). + Thanks @domdomegg. + +# 2024-06-28, 13.0.1 + +- Fix: #3227 generated bundle containing `catch` blocks without parameters. +- Fix: #2348 update type definitions of the `Parser` methods (#3226). + Thanks @orelbn. + +# 2024-05-31, 13.0.0 -- Add type definitions for function `rotationMatrix` (#2860). +Breaking changes: + +- Change `isZero`, `isPositive`, and `isNegative` to respect `config.epsilon` + (#3139, #2838). +- Change the behavior of the internal `nearlyEqual` to align with Python and + Julia (#3152, #2838) +- Upgrade to `fraction.js@4.3.7`, + see . +- Dropped support for JavaScript engines that do not fully support ES6 or + `bigint`, or are not actively maintained. ES2020 is now the minimum required + EcmaScript version. + +Non-breaking changes: + +- Implemented support for `bigint` (#3207, #3207) +- Implemented a new config option `config.numberFallback` needed for `bigint` + (#3207). +- Internal: refactored tooling to ES modules and upgraded all devDependencies. + +# 2024-05-31, 12.4.3 + +- Fix: serialization of Units without a value, see #1240. +- Fix: outdated, incorrect documentation about the order of precedence for + operator modulus `%`. See #3189. +- Fix: #3197 improve `quantileSeq` type definitions (#3198). Thanks @domdomegg. + +# 2024-04-24, 12.4.2 + +- Fix #3192: function `isNaN` returns `false` for `NaN` units in a matrix or + array (#3193). Thanks @lgerin. +- Fix: #3180 fix type definitions of functions `add` and `multiply` to allow + more than two arguments. +- Docs: correct the docs about `traverse` returning void (#3177). + Thanks @rohildshah. + +# 2024-03-13, 12.4.1 + +- Docs: implement an interactive version of the Lorenz example, and show the + chart full screen (#3151). Thanks @dvd101x. +- Fix #3172: simplify `"true and true"`. +- Fix #3163: `toTex` wrongly returning `Infinity` for large BigNumbers. +- Fix #3162: add license information about CSParse (#3164). +- Fix #3175: cannot delete units using `math.Unit.deleteUnit`. +- Fix: faster startup time of the CLI and REPL by loading the bundle. +- Fix: remove using polyfill.io inside the example + `pretty_printing_with_mathjax.html` (#3167). Thanks @SukkaW. + +# 2024-02-22, 12.4.0 + +- Feat: implement support for trailing commas in matrices (#3154, #2968). + Thanks @dvd101x. +- Feat: improve the performance of `multiply` a lot by adding matrix type + inferencing (#3149). Thanks @RandomGamingDev. +- Fix: #3100 function `round` not handling round-off errors (#3136). + Thanks @BrianFugate. +- Fix: `PartitionedMap` and `ObjectWrappingMap` missing a property + `Symbol.iterator`, causing problems when trying `new Map(scope)` (#3156). +- Fix: type definitions of function `mode` (#3153). Thanks @rich-martinez. +- Docs: describe method `getAllAsMap` in the Parser docs (#3158, #3157). + Thanks @dvd101x. + +# 2024-02-08, 12.3.2 + +- Improved the performance of custom defined functions in the expression + parser (#3150). +- Fix: #3143 cannot use `and` and `or` inside a function definition. + Regression since `v12.1.0` (#3150). + +# 2024-02-01, 12.3.1 + +- Improved the typings of the arguments of `ArrayNode`, `FunctionNode`, + `IndexNode`, `OperatorNode`, and `RelationalNode` (#3123). Thanks @sylee957. +- Added a fully featured code editor example with CodeMirror and Katex (#3027). + Thanks @dvd101x. +- Fix: #3114 build warnings related to a number of wrong `/* #__PURE__ */` + annotations. +- Fix: #3142 support BigNumber values for the options of function `format`: + `precision`, `wordSize`, `lowerExp`, `upperExp`. Support BigNumber values + for the option `wordSize` in the functions `hex`, `bin`, and `oct`. +- Fix: #3125 type definitions of function `hypot` (#3144). + Thanks @silentmissile. +- Fix: #3141 `help(config)` altering the actual `config` when evaluating the + examples. +- Docs: #3145 fix documentation about REPL, it does require a build step + nowadays. + +# 2024-01-12, 12.3.0 + +- Implement support new metric prefixes: `ronna` (`R`), `quetta` (`Q`), + `ronto` (`r`), and `quecto` (`q`) (#3113, #3112). Thanks @AlexEdgcomb. +- Fix a bug converting a unitless unit (#3117). Thanks @costerwi. +- Fix: #3097 `toSI()` wrongly converting `degC` (#3118). Thanks @costerwi. + +# 2023-12-20, 12.2.1 + +- Fix #3109: method `Node.toHTML` not accepting a custom `handler`. + +# 2023-12-08, 12.2.0 + +- Feat: lazy evaluation of operators `and`, `or`, `&`, `|` (#3090, #3101, + #2766). Thanks @smith120bh. +- Fix: passing a 4th argument with a scope to raw functions. +- Fix: #3096 embedded docs of eigs throwing an error. + +# 2023-11-17, 12.1.0 + +- Feat: Extend function `round` with support for units (#2761, #3095). +- Feat: Extend function `mod` with support for negative divisors in when + using `BigNumber` or `Fraction` (#3087). +- Fix: #3092 a typo in an error message when converting a string into a number. +- Fix: #3094 function `derivative` mutates the input expression when it fails. + +# 2023-10-26, 12.0.0 + +Breaking changes: + +- Fix #2879, #2927, #3014: change the confusing interface of `eigs` (#3037), + thanks @gwhitney. + Before, functions `eigs` returned an object: + + ``` + { values: MathCollection; vectors: MathCollection } + ``` + + where `vectors` was a 2d matrix of which the columns contained the vectors. + This is changed to `eigs` returning an object: + + ``` + { + values: MathCollection + eigenvectors: Array<{ + value: number | BigNumber + vector: MathCollection + }> + } + ``` + + Where `eigenvectors` is an array containing an object with the corresponding + eigenvalue and vector. +- Refactored the TypeScript type definitions to make them work with a `NodeNext` + module resolution (#3079, #2919). + - Type `MathJsStatic` is renamed to `MathJsInstance`. + - Type `FactoryDependencies` is deprecated, use `MathJsFactory` instead, and + import dependency maps directly from the library. +- Change the assignment operator of `.toTex()` output from `:=` to `=` (see + #2980, #2987). +- Drop official support for Node.js 14 and 16. + +Features: + +- Function `eigs` now has an option to turn off calculation of eigenvectors + (#3057, #2180). Thanks @gwhitney. + +Fixes: + +- Find eigenvectors of defective matrices (#3037). Thanks @gwhitney. + +# 2023-10-26, 11.12.0 + +- Implemented function `subtractScalar` (#3081, #2643), thanks @vrushaket. +- Fix #3073: function format not escaping control characters and double + quotes (#3082). +- Fix: function `clone` not throwing an error when passing an unsupported + type like a function. +- Fix: #2960 add type definition of function `symbolicEqual` (#3035), + thanks @juancodeaudio. + +# 2023-10-11, 11.11.2 + +- Fix #3025: improve handling of matrices and error handling + in function `corr` (#3030). Thanks @vrushaket. +- Fix #3074: improve error message when using function `max` in `derivative`. +- Fix #3073: fix parsing quotes inside a string. +- Fix #2027: cannot use named operators like `to` or `mod` as property name. + +# 2023-09-20, 11.11.1 + +- Fix #2989: use one-based indices in `print` in the parser (#3009). + Thanks @dvd101x. +- Fix #2936: `mod` sometimes giving wrong results due to internal round-off + errors (#3011). Thanks @praisennamonu1. +- Internal refactor of `quantileSeq`, and fixed the embedded help (#3003). + Thanks @dvd101x. +- Updated dependencies and devDependencies. + +# 2023-09-05, 11.11.0 + +- Implement function `corr` to calculate the correlation between two matrices + (#3015, #2624). Thanks @vrushaket. +- Lock `fraction.js` at version `4.3.4` for now, see #3024, 3022, + . + +# 2023-08-31, 11.10.1 + +- Upgrade to `fraction.js@4.3.4`, see #3022. +- Fix #3020: `lruQueue` using the global `hasOwnProperty` which may be + polluted. +- Add support for prefixes for the unit `erg`, and restrict prefixes of the + unit `joule` to only long prefixes like `kilo` and no short prefixes + like `k` (#3019). Thanks @costerwi. +- Add a new browser example `examples/browser/lorenz.html` that uses `solveODE` + and plots the result in a chart (#3018). Thanks @dvd101x. + +# 2023-08-23, 11.10.0 + +- Extend function `quantileSeq` with support for a `dimension` (#3002). + Thanks @dvd101x. +- Implement #2735: Support indexing with an array of booleans, for + example `a[[true, false, true]]` and `a[a > 2]` (#2994). Thanks @dvd101x. +- Implement function `zeta` (#2950, #2975, #2904). Thanks @Bobingstern. +- Fix #2990: `DenseMatrix` can mutate input arrays (#2991). + +# 2023-07-24, 11.9.1 + +- Fix a security vulnerability in `FunctionNode` and `SymbolNode` allowing + arbitrary code execution via `math.evaluate`. Thanks Harry Chen. +- Fix #3001: mathjs bundle containing `new Function(...)` (CSP issue). + +# 2023-07-19, 11.9.0 + +- Implement function `solveODE` (#2958). Thanks @dvd101x. +- Implement functions `zpk2tf` and `freqz` (#2988, #2969). Thanks @alykhaled. +- Implement support for units in function `range` (#2997). Thanks @dvd101x. +- Fix #2974: `simplify` puts plus and minus signs next to each other (#2981). + Thanks @MaybePixem. +- Fix #2973: fixes and improvements in the embedded docs (#2976). + Thanks @dvd101x. +- Fix #2996: two errors in the examples in the documentation about Expression + trees. +- Fix round-off errors near zero when converting temperatures (#2962). + Thanks @costerwi. +- Refactored function `range`, reducing the amount of code (#2995). + Thanks @dvd101x. + +# 2023-06-20, 11.8.2 + +- Fix #2971: improve typings of statistics functions `min`, `max`, `mean`, + `median`, `mode`, `std`, `sum`, `prod`, `variance`. Fixes a regression + introduced in v11.8.1. +- Fix #2972: type definitions of `Unit.divide(Unit)` have a wrong return type. + +# 2023-06-13, 11.8.1 + +- Fix #2964: issue in function `distance` when calculate the distance from + a point to a line (#2965). Thanks @Kiku-CN. +- Fix `math.format` not working correctly for `engineering` notation when using + BigNumbers and for `fixed` notation with `precision: 0` configured (#2956). + Thanks @mgreminger. +- Fix #2880: not possible to map cube root `cbrt`. +- Fix #2938: make the syntax description of all functions consistent in the + docs (#2941). Thanks @dvd101x. +- Fix #2954: improve the TypeScript definitions the return type of functions + `min` and `max` (#2955). Thanks @Maxim-Mazurok. +- Fix #2959: typo in an example in the docs. Thanks @kunalagrwl. +- Drop official support for Node.js 14, has reached end of life. + +# 2023-04-03, 11.8.0 + +- Extended functions `fraction`, `bignumber`, and `number` with support for + units, see #2918 (#2926). +- Implemented aliases `amp` and `amps` for unit `ampere` (#2917). + Thanks @veggiesaurus. +- Improve TypeScript definitions of function `gcd` (#2922). Thanks @brunoSnoww. +- Fix #2923: improve docs of the function `distance` (#2924). Thanks @tmtron. + +# 2023-03-15, 11.7.0 + +- Implement #2567: accept array as parameter for function `gcd` (#2878). + Thanks @jakubriegel. +- Fix #2908: improvements in the docs and examples of functions + `partitionSelect`, `diff`, `expm1`, `round`, `nthRoots`, `sign`, + `rigthArithShift`, `setIsSubset`, `setSize`, and the docs about units. + Thanks @tmtron. +- Fix #2907: determinant of empty matrix should be 1. +- Refactor index.d.ts by writing function declarations using a generic, + reducing a lot of repetition (#2913). Thanks @brunoSnoww. + +# 2023-02-24, 11.6.0 + +- Implement broadcasting for the following functions and their corresponding + operator: `add`, `dotDivide`, `dotMultiply`, `dotPow`, `gcd`, `lcm`, `mod`, + `nthRoot`, `subtract`, `bitAnd`, `bitOr`, `bitXor`, `leftShift`, + `rightArithShift`, `rightLogShift`, `and`, `or`, `xor`, `compare`, + `compareText`, `equal`, `larger`, `largerEq`, `smaller`, `smallerEq`, + `unequal`, `atan2` and `to` (#2895, #2753). Thanks @dvd101x. +- Implement support for non-power-of-2 fft (#2900, #2577). Thanks @cyavictor88. +- Fix #2888: update type definitions of function `unit` to allow creating a + unit from a fraction or complex number. +- Fix #2892: an error in the examples of the embedded help of function `sort`. +- Fix #2891: functions `column` and `row` sometimes returning a scalar number. +- Fix #2896: define the fourth argument of function `intersect` as optional + in the TypeScript definitions. Thanks @wodndb. +- Fix: quantileSeq not accepting a matrix as second argument `prob` (see #2902). +- Fix broken examples in functions `to`, `distance`, `getMatrixDataType`, + `subset`, and `max` (see #2902). + +# 2023-01-31, 11.5.1 + +- Add type definitions for function `rotationMatrix` (#2860). Thanks @brunoSnoww. -- Add type signature for `lusolve(LUDecomposition, ...)` (#2864). +- Add type signature for `lusolve(LUDecomposition, ...)` (#2864). Thanks @evanmiller. - +- Fix #2873: the rocket_trajectory_optimization.html example being partly + broken. Thanks @dvd101x. +- Fix #2871: coverage report broken (#2877). Thanks @bornova. +- Fix #2883: update documentation for stat functions, describe missing syntax. +- Fix #2884: fix examples in the embedded docs of function `pow` and some other + functions. +- Fix type definition of function `complex` for one numeric input (#2886), + thanks @ariymarkowitz. +- Fix type definitions of `map()` and `forEach()` (#2887), thanks @xiaohk. +- Fix #2606: improve type definitions of `dotMultiply`, `dotPow` and + `dotDivide` (#2890). Thanks @brunoSnoww. # 2022-12-05, 11.5.0 -- Improve `simplify` rule matches in non-commutative contexts (#2841). +- Improve `simplify` rule matches in non-commutative contexts (#2841). Thanks @samueltlg. - Simplify: add rules and restructure tests for non-commutative contexts (#2847). Thanks @samueltlg. @@ -18,61 +396,54 @@ - Fix TypeScript types for `multiply()` with `number[]` and `number[][]` (#2852). Thanks @hfhchan. - # 2022-11-18, 11.4.0 - Implemented more wildcards to describe rules for `simplify`, making it easier for example to describe unary minus (#1915). Thanks @thatcomputerguy0101. -- Implemented functions `schur`, `sylvester`, and `lyap` (#2646). +- Implemented functions `schur`, `sylvester`, and `lyap` (#2646). Thanks @egidioln. -- Implemented function `polynomialRoot`, and use it in a benchmark (#2839). +- Implemented function `polynomialRoot`, and use it in a benchmark (#2839). Thanks @gwhitney. -- Fix #2825 partly: improve simplifying operations on constants in +- Fix #2825 partly: improve simplifying operations on constants in non-commutative contexts (#2827). Thanks @samueltlg. -- Fix #2840: a bug in the docs and type definitions of `Node.traverse` and +- Fix #2840: a bug in the docs and type definitions of `Node.traverse` and `Node.forEach`, they do return `void`. - # 2022-11-07, 11.3.3 -- Fix #2830: Prevent inserting zero values when creating a `SparseMatrix` from a +- Fix #2830: Prevent inserting zero values when creating a `SparseMatrix` from a `DenseMatrix` (#2836). Thanks @AlexandreAlvesDB. - Fix #2835: a regression in the type definitions of `FunctionNode`, introduced in `v11.3.2`. See #2733. Thanks @dsteve. - # 2022-10-25, 11.3.2 -- Add generics to remaining Node type definitions (#2733). Thanks @mattvague. -- Allow unit prefixes for (absolute) temperatures `kelvin`, `rankine`, +- Add generics to remaining Node type definitions (#2733). Thanks @mattvague. +- Allow unit prefixes for (absolute) temperatures `kelvin`, `rankine`, `celsius`, and `fahrenheit` (#2824). Thanks @jfeist - # 2022-10-19, 11.3.1 - Fix #2809: code completion issues in some IDE's (#2812). -- Fix #2818: throw an error when a function assignment has duplicate +- Fix #2818: throw an error when a function assignment has duplicate parameter names (#2819). - Update `decimal.js` to version `10.4.2`. - # 2022-10-11, 11.3.0 -- Allow creating new subclasses of `Node` in TypeScript (#2772). +- Allow creating new subclasses of `Node` in TypeScript (#2772). Note that this disables being able to narrow MathNodes by using the `.type` property. Use typeguards like `isOperatorNode(...)` instead (see #2810). Thanks @mattvague. - Fix #2793: `flatten()` cloning entries of array/Matrix (#2799). -- Fix #2627: TypeScript definitions of `pinv` missing (#2804). +- Fix #2627: TypeScript definitions of `pinv` missing (#2804). Thanks @HanchaiN. - Update dependencies to `decimal.js@10.4.1`. - # 2022-09-13, 11.2.1 - Fix doc generator being broken, not generating a function reference. - # 2022-09-12, 11.2.0 - Implement function `isRelationalNode` (#2731). Thanks @isaacbyr. @@ -83,49 +454,46 @@ - Fixed documentation of unit `min` which means `minutes`, not `minim` (#2773). Thanks @jasonhornsby. - # 2022-08-23, 11.1.0 - Add Unit constructor from value and pure (valueless) Unit (#2628). Thanks @costerwi - Fix #2144: `examples/advanced/custom_loading.js` was broken. -- Fix JSON `replacer` function missing in the TypeScript definitions. +- Fix JSON `replacer` function missing in the TypeScript definitions. Thanks @mattvague. -- Update dependencies to `typed-function@4.1.0` and `decimal.js@10.4.0`. - +- Update dependencies to `typed-function@4.1.0` and `decimal.js@10.4.0`. # 2022-07-25, version 11.0.1 - Fix #2632: TypeScript issue of `simplifyConstant` and `simplifyCore` not having a return type defined. - # 2022-07-23, version 11.0.0 !!! BE CAREFUL: BREAKING CHANGES !!! Breaking changes: -- Dropped official support for IE11. -- Upgraded to `typed-function@3`, see [josdejong/typed-function/HISTORY.md](https://github.com/josdejong/typed-function/blob/develop/HISTORY.md#2022-05-12-version-300). Thanks @gwhitney. Most importantly: - - Conversions now have preference over `any`. - - The `this` variable is no longer bound to the typed function itself. - - The properties `typed.types`, `typed.conversions`, and `typed.ignore` +- Dropped official support for IE11. +- Upgraded to `typed-function@3`, see [josdejong/typed-function/HISTORY.md](https://github.com/josdejong/typed-function/blob/develop/HISTORY.md#2022-05-12-version-300). Thanks @gwhitney. Most importantly: + - Conversions now have preference over `any`. + - The `this` variable is no longer bound to the typed function itself. + - The properties `typed.types`, `typed.conversions`, and `typed.ignore` have been removed. - - There are new static functions available like `typed.referTo`, + - There are new static functions available like `typed.referTo`, `typed.referToSelf`, `typed.addTypes`, `typed.addConversions`. - Implement amended "Rule 2" for implicit multiplication (#2370, #2460): - when having a division followed by an implicit multiplication, the division - gets higher precedence over the implicit multiplication when (a) the - numerator is a constant with optionally a prefix operator (`-`, `+`, `~`), - and (b) the denominator is a constant. For example: formerly `-1 / 2 x` was + when having a division followed by an implicit multiplication, the division + gets higher precedence over the implicit multiplication when (a) the + numerator is a constant with optionally a prefix operator (`-`, `+`, `~`), + and (b) the denominator is a constant. For example: formerly `-1 / 2 x` was interpreted as `-1 / (2 * x)` and now it is interpreted as `(-1 / 2) * x`. Thanks @gwhitney. - Drop elementwise matrix support for trigonometric functions, exp, log, gamma, - square, sqrt, cube, and cbrt to prevent confusion with standard matrix - functions (#2440, #2465). Instead, use `math.map(matrix, fn)`. + square, sqrt, cube, and cbrt to prevent confusion with standard matrix + functions (#2440, #2465). Instead, use `math.map(matrix, fn)`. Thanks @gwhitney. -- Simplify: convert equivalent function calls into operators, for example, +- Simplify: convert equivalent function calls into operators, for example, `add(2, x)` will now be simplified into `2 + x` (#2415, #2466). Thanks @gwhitney. - Removed the automatic conversion from `number` to `string` (#2482). @@ -133,25 +501,25 @@ Breaking changes: - Fix #2412: let function `diff` return an empty matrix when the input contains only one element (#2422). - Internal refactoring in the `simplifyCore` logic (#2490, #2484, #2459). - The function `simplifyCore` will no longer (partially) merge constants, that - behavior has been moved to `simplifyConstant`. The combination of - `simplifyConstant` and `simplifyCore` is still close to the old behavior - of `simplifyCore`, but there are some differences. To reproduce the same - behavior as the old `simplifyCore`, you can use - `math.simplify(expr, [math.simplifyCore, math.simplifyConstant])`. - Thanks to the refactoring, `simplify` is more thorough in reducing constants. + The function `simplifyCore` will no longer (partially) merge constants, that + behavior has been moved to `simplifyConstant`. The combination of + `simplifyConstant` and `simplifyCore` is still close to the old behavior + of `simplifyCore`, but there are some differences. To reproduce the same + behavior as the old `simplifyCore`, you can use + `math.simplify(expr, [math.simplifyCore, math.simplifyConstant])`. + Thanks to the refactoring, `simplify` is more thorough in reducing constants. Thanks @gwhitney. -- Disable support for splitting rest parameters in chained calculations +- Disable support for splitting rest parameters in chained calculations (#2485, #2474). For example: `math.chain(3).max(4, 2).done()` will now throw - an error rather than return `4`, because the rest parameter of - `math.max(...number)` has been split between the contents of the chain and + an error rather than return `4`, because the rest parameter of + `math.max(...number)` has been split between the contents of the chain and the arguments to the max call. Thanks @gwhitney. -- Function `typeOf` now returns `function` (lowercase) for a function instead +- Function `typeOf` now returns `function` (lowercase) for a function instead of `Function` (#2560). Thanks @gwhitney. Non-breaking changes: -- Fix #2600: improve the TypeScript definitions of `simplify`. +- Fix #2600: improve the TypeScript definitions of `simplify`. Thanks @laureen-m and @mattvague. - Fix #2607: improve type definition of `createUnit`. Thanks @egziko. - Fix #2608: clarify the docs on the need to configure a smaller `epsilon` @@ -161,70 +529,62 @@ Non-breaking changes: - Fix #2621: add TypeScript definitions for `count` (#2622). Thanks @Hansuku. - Improved TypeScript definitions of `multiply` (#2623). Thanks @Windrill. - # 2022-06-28, version 10.6.4 - Improve TypeScript definitions of the `factory` function, thanks @mattvague. - # 2022-06-24, version 10.6.3 -- Revert the TypeScript definition fixes for `factory` applied in `v10.6.2`, +- Revert the TypeScript definition fixes for `factory` applied in `v10.6.2`, they give some complications. - # 2022-06-24, version 10.6.2 - Improve TypeScript definitions of `ParenthesisNode`. Thanks @mattvague. -- Change the TypeScript definition of `MathNodeCommon['type']` into a less - strict string, so it is possible to extend with new Node classes. +- Change the TypeScript definition of `MathNodeCommon['type']` into a less + strict string, so it is possible to extend with new Node classes. Thanks @mattvague. - Improve TypeScript definitions of the `factory` function, thanks @mattvague. - # 2022-05-31, version 10.6.1 -- Improve the TypeScript types For `OperatorNode`: you can now define generic +- Improve the TypeScript types For `OperatorNode`: you can now define generic types like `OperatorNode<'+', 'add'>`. Thanks @mattvague. - # 2022-05-24, version 10.6.0 -- Implementation of fourier transform functions `fft` and `ifft` (#2540). +- Implementation of Fourier transform functions `fft` and `ifft` (#2540). Thanks @HanchaiN. - Fix TypeScript types not being listed in the exported fields (#2569). - Thanks @mattvague. + Thanks @mattvague. - Large improvements in TypeScript definitions for chained expressions (#2537). Thanks @mattvague. -- Fix #2571: improve TypeScript definition of functions `clone` and `cloneDeep` +- Fix #2571: improve TypeScript definition of functions `clone` and `cloneDeep` (#2572). Thanks @mattvague. - Fix the first argument of `derivative` holding the expression not correctly being converted when using `.toTex()` (#2564). Thanks @mattvague. - # 2022-05-11, version 10.5.3 -- Fix #2337: npm package containing examples and docs to solve security +- Fix #2337: npm package containing examples and docs to solve security vulnerabilities being reported on the examples and their dependencies. - Fix core, construction, and some other functions missing in docs. - Drop official support for Node.js 12 which has reached its end of life. - # 2022-05-09, version 10.5.2 -- Fix #2553: `@types/mocha` defined in `dependencies` instead of +- Fix #2553: `@types/mocha` defined in `dependencies` instead of `devDependencies`, causing problems in projects that use a different version of this dependency. Thanks @Kolahzary. - Fix #2550: remove `examples/node_modules` folder from the npm package. - Fix #2528: improve contribution guidelines (#2548). -- Document `SymbolNode.onUndefinedSymbol` and +- Document `SymbolNode.onUndefinedSymbol` and `FunctionNode.onUndefinedFunction`. - # 2022-05-02, version 10.5.1 - Fix #2526, #2529: improve TypeScript definitions of function `round`, `fix`, - `floor`, `ceil`, and `nthRoot`, and improved the number only implementations + `floor`, `ceil`, and `nthRoot`, and improved the number only implementations of those functions (#2531, #2539). Thanks @simlaticak and @gwhitney. - Fix #2532: matrix index symbol `end` not working when used inside a sub-expression. @@ -232,12 +592,11 @@ Non-breaking changes: (e.g., to avoid spurious duplicates in list). (#2543) - Add type definitions of function `resolve` (#2536). Thanks @mattvague. - # 2022-04-19, version 10.5.0 -- Implement #1563: function `pinv`, Moore–Penrose inverse (#2521). +- Implement #1563: function `pinv`, Moore–Penrose inverse (#2521). Thanks @HanchaiN. -- Optimize function `det` for integers by switching to the Bareiss algorithm: +- Optimize function `det` for integers by switching to the Bareiss algorithm: no more round-off errors for integer input (#2516). Thanks @HanchaiN. - Implement #2463: allow negative integer powers of invertible square matrices (#2517). Thanks @HanchaiN. @@ -248,7 +607,6 @@ Non-breaking changes: - Fix #2526: update TypeScript definition of `ceil` (#2531). Thanks @simlaticak - Change mocha reporter to 'dot' to avoid excessively long log files. (#2520) - # 2022-04-08, version 10.4.3 - Fix #2508: improve the precision of stirlingS2 (#2509). Thanks @gwhitney. @@ -256,14 +614,13 @@ Non-breaking changes: of function `log` (#2515). Thanks @gwhitney. - Improve the documentation on operator `;` (#2512). Thanks @gwhitney. - # 2022-03-29, version 10.4.2 - Fix #2499: different behavior for unit conversion "degC" and "K" (#2501). - Also disables getting the sign for units with an offset, which is ambiguous. + Also disables getting the sign for units with an offset, which is ambiguous. Thanks @gwhitney. - Fix #2503: fix an issue in `log()` for complex numbers in which the imaginary - part is much larger in absolute value than the real part, fixed in + part is much larger in absolute value than the real part, fixed in `complex.js@2.1.0` (#2505), thanks @gwhitney, @infusion. - Fix #2493: unclear error message when an entity that is not a function is being called as a function (#2494). Thanks @gwhitney. @@ -273,10 +630,9 @@ Non-breaking changes: comparison tolerance. It was already being called this way, but was silently ignoring the tolerance. Thanks @yifanwww. - # 2022-03-23, version 10.4.1 -- Improve TypeScript definitions for function `unit` (#2479). +- Improve TypeScript definitions for function `unit` (#2479). Thanks @SinanAkkoyun. - Add tests for type declarations (#2448). Thanks @samestep. - Further improvement to TypeScript definitions of `std` and `variance` @@ -290,7 +646,6 @@ Non-breaking changes: numbers (#2496). Thanks @gwhitney. - Update project dependencies and devDependencies. - # 2022-03-07, version 10.4.0 - Fix #2461: make sure `simplifyCore` recurses over all binary nodes (#2462). @@ -299,11 +654,10 @@ Non-breaking changes: (#2455). Thanks @NattapongSiri. - Fix #1633: implement a `cumsum` function generating cumulative sums of a list of values or a matrix. (#1870). Thanks @hjonasson. -- Upgrade to the latest version of `Fraction.js`, having more strict input, +- Upgrade to the latest version of `Fraction.js`, having more strict input, only accepting an integer numerator and denominator. See #2427. - Fix typo in documentation example for `format`. (#2468) Thanks @abranhe. -- Write unit tests for all jsdoc examples. See #2452. Thanks @gwhitney. - +- Write unit tests for all jsdoc examples. See #2452. Thanks @gwhitney. # 2021-03-02, version 10.3.0 @@ -311,38 +665,35 @@ Non-breaking changes: - Fix #2441, #2442: support passing a function as argument to functions created in the expression parser (#2443). Thanks @gwhitney. - Fix #2325: improve documentation of subset indices (#2446). Thanks @gwhitney. -- Fix #2439: fix a bug in `complexEigs` in which real-valued norms were +- Fix #2439: fix a bug in `complexEigs` in which real-valued norms were inadvertently being typed as complex numbers (#2445). Thanks @gwhitney. - Fix #2436: improve documentation and error message of function `map` (#2457). Thanks @gwhitney. - # 2022-03-01, version 10.2.0 -- Implemented context options to control simplifications allowed in `simplify`, +- Implemented context options to control simplifications allowed in `simplify`, see #2399, #2391. Thanks @gwhitney. -- Implemented function `leafCount` as a first simple measure of the complexity +- Implemented function `leafCount` as a first simple measure of the complexity of an expression, see #2411, #2389. Thanks @gwhitney. - Fix #2413: improve `combinations` to return an integer result without rounding errors for larger values, see #2414. Thanks @gwhitney. -- Fix #2385: function `rotate` missing in TypeScript definitions. +- Fix #2385: function `rotate` missing in TypeScript definitions. Thanks @DIVYA-19. - Fix #2450: Add BigNumber to parameter type in `math.unit` and add TypeScript types for `Unit.simplify` and `Unit.units` (#2353). Thanks @joshhansen. - Fix #2383: detect infinite loops in `simplify` (#2405). Thanks @gwhitney. -- Fix #1423: collect like factors and cancel like terms in sums (#2388). +- Fix #1423: collect like factors and cancel like terms in sums (#2388). Thanks @gwhitney. - # 2022-02-02, version 10.1.1 - Improvements and fixes in function `simplify`, thanks @gwhitney: - Fix #2393: regression bug in `simplify('2-(x+1)')`. - Ad option `consoleDebug` to `simplify` to see what is going on. -- Fix TypeScript definition of `ConfigOptions`, which was missing option +- Fix TypeScript definition of `ConfigOptions`, which was missing option `predictable`. - # 2022-01-15, version 10.1.0 - Implemented function `invmod`, see #2368, #1744. Thanks @thetazero. @@ -353,29 +704,26 @@ Non-breaking changes: - Fix #2379: add embedded documentation for function `print`. - Remove broken example from the embedded documentation of function `forEach`. - # 2021-12-29, version 10.0.2 - Fix #2156: simplify expressions like `-1 / (-x)` to `1/x`. Thanks @ony3000. - Fix #2363: remove a redundant part of the regex to split a number. -- Fix #2291: add support for fractions in function `intersect`. +- Fix #2291: add support for fractions in function `intersect`. Thanks @thetazero. - Fix #2358: bug in `SparseMatrix` when replacing a subset of a matrix with a non-consecutive index. Thanks @Al-0. - # 2021-12-22, version 10.0.1 - Fix #1681: function `gamma` giving inaccurate complex results in some cases. Thanks @kmdrGroch. - Fixed a typo in an example, see #2366. Thanks @blackwindforce. - # 2021-11-03, version 10.0.0 !!! BE CAREFUL: BREAKING CHANGES IN THE TYPESCRIPT DEFINITIONS !!! -- Improvements to the Typescript typings (commit fc5c202e). +- Improvements to the Typescript typings (commit fc5c202e). Thanks @joshhansen. First introduced in v9.5.1, but reverted because it contains breaking changes. @@ -384,51 +732,45 @@ Non-breaking changes: - Fixed a typo in the TypeScript definition of toHTML. Thanks @TheToto. - # 2021-11-03, version 9.5.2` - Revert the improvements to the Typescript typings because they contain breaking changes. The improvements will be published in v10.0.0. See #2339. - # 2021-10-13, version 9.5.1 -- Various improvements to the Typescript typings. +- Various improvements to the Typescript typings. Thanks @joshhansen and @DianaTdr. - # 2021-09-22, version 9.5.0 -- Implemented support for calculations with percentage, see #2303. +- Implemented support for calculations with percentage, see #2303. Thanks @rvramesh. -- Fix #2319: make the API of `Parser.evaluate` consistent with `math.evaluate`: +- Fix #2319: make the API of `Parser.evaluate` consistent with `math.evaluate`: support a list with expressions as input. - Improved documentation of function `setCartesian`. Thanks @fieldfoxWim. - # 2021-09-15, version 9.4.5 -- Improved the performance of `Node.equals` by improving the internal +- Improved the performance of `Node.equals` by improving the internal function `deepStrictEqual`. Thanks @tomlarkworthy. - Fixes in the TypeScript definitions: - - Define `hasNumericValue`. Thanks @write2kcl. + - Define `hasNumericValue`. Thanks @write2kcl. - Define `MathNode.isRelationalNode`. Thanks @m93a. - Fix typo in `MathNode.isConditionalNode`. Thanks @m93a. - # 2021-07-07, version 9.4.4 -- Fixed `ArrayNode.toTex()`: remove the row delimiter on the last row, +- Fixed `ArrayNode.toTex()`: remove the row delimiter on the last row, see #2267. Thanks @davidtranhq. - Fix #2269: `intersect` not returning `null` for matrix input. Thanks @m93a. - Fix #2245: mathjs not working in IE11 anymore due to a missing polyfill for - `Symbol`. The browser bundle now includes the necessary polyfills (it is + `Symbol`. The browser bundle now includes the necessary polyfills (it is larger now because of that, see also #2266). Thanks @m93a. - Update dependencies (`complex.js@2.0.15`, `decimal.js@10.3.1`) -- Drop official support for node.js 10, which has reached end of life. +- Drop official support for node.js 10, which has reached end of life. See #2258. - # 2021-06-23, version 9.4.3 - Fix #2222: mathjs polluting the `Decimal` prototype. Thanks @m93a. @@ -436,17 +778,15 @@ Non-breaking changes: properties named `e`. - Fixes in the TypeScript definitions: - function `floor`, #2159, #2246. Thanks @write2kcl. - - function `simplify`, see #2252. Thanks @nitroin. + - function `simplify`, see #2252. Thanks @nitroin. - Upgraded to `decimal.js@10.3.0` - # 2021-06-05, version 9.4.2 -- Implemented iterative eigenvalue finder for `eigs`, making it much more +- Implemented iterative eigenvalue finder for `eigs`, making it much more robust. See #2179, #2237. Thanks @m93a. - Improved TypeScript definitions of function `parse`. Thanks @OpportunityLiu. - # 2021-05-24, version 9.4.1 - Fix #2100: add TypeScript declaration for `eigs`. Thanks @andrebianchessi. @@ -454,71 +794,64 @@ Non-breaking changes: - Update readme regarding TypeScript definition files. Thanks @dhritzkiv. - Update to `fraction.js@4.1.1` - # 2021-05-16, version 9.4.0 -- Implemented support to use objects with a `Map` interface as scope, +- Implemented support to use objects with a `Map` interface as scope, see #2143, #2166. Thanks @jhugman. - Extend `eigs` to support general complex matrices, see #1741. Thanks @m93a. - DenseMatrix and SparseMatrix are now iterable, see #1184. Thanks @m93a. -- Implemented utility functions `matrixFromRows`, `matrixFromColumns`, and +- Implemented utility functions `matrixFromRows`, `matrixFromColumns`, and `matrixFromFunction`, see #2155, #2153. Thanks @m93a. - Added TypeScript definitions to the project, making it redundant to install - `@types/mathjs`, and making it easier to improve the definitions. See #2187, + `@types/mathjs`, and making it easier to improve the definitions. See #2187, #2192. Thanks @CatsMiaow. - Upgraded dependencies - `complex.js@2.0.13` (fixing #2211). Thanks @infusion - `fraction.js@4.1.0` (`pow` now supporting rational exponents). - Fix #2174: function `pickRandom` having no name. Thanks @HK-SHAO. - Fix #2019: VSCode auto import keeps adding import { null } from 'mathjs'. -- Fix #2185: Fix TypeScript definition of unit division, which can also return +- Fix #2185: Fix TypeScript definition of unit division, which can also return a number. - Fix #2123: add type definitions for functions `row` and `column`. - Fix some files not exposed in the package, see #2213. Thanks @javiermarinros. - # 2021-04-12, version 9.3.2 -- Fix #2169: mathjs requesting `@babel/runtime` dependency. +- Fix #2169: mathjs requesting `@babel/runtime` dependency. Regression introduced in `v9.3.1`. - # 2021-04-10, version 9.3.1 -- Fix #2133: strongly improved the performance of `isPrime`, see #2139. +- Fix #2133: strongly improved the performance of `isPrime`, see #2139. Thanks @Yaffle. - Fix #2150: give a clear error "Error: Undefined function ..." instead when evaluating a non-existing function. -- Fix #660: expose internal functions `FunctionNode.onUndefinedFunction(name)` +- Fix #660: expose internal functions `FunctionNode.onUndefinedFunction(name)` and `SymbolNode.onUndefinedSymbol(name)`, allowing to override the behavior. By default, an Error is thrown. - # 2021-03-10, version 9.3.0 - Implemented support for parsing non decimal numbers with radix point, see #2122, #2121. Thanks @clnhlzmn. - Fix #2128: typo in docs of `luSolveAll` and `usolveAll`. - # 2021-02-03, version 9.2.0 -- Implemented function `count` to count the total elements in a matrix, +- Implemented function `count` to count the total elements in a matrix, see #2085. Thanks @Josef37. - Fix #2096: cleanup old reference to external dependency `crypto`. -- Some refactoring in the code to remove duplications, see #2093. +- Some refactoring in the code to remove duplications, see #2093. Thanks @Josef37. - # 2021-01-27, version 9.1.0 - Extended function `reshape` with support for a wildcard `-1` to automatically - calculate the remaining size, like `reshape([1, 2, 3, 4, 5, 6], [-1, 2])` + calculate the remaining size, like `reshape([1, 2, 3, 4, 5, 6], [-1, 2])` which will output `[[0, 1], [2, 3], [4, 5]]`. See #2075. Thanks @Josef37. - Fix #2087: function `simplify` ignores second argument of `log`, for example in `simplify('log(e, 9)')` . Thanks @quentintruong. - # 2021-01-16, version 9.0.0 - Improved support for bin, hex, and oct literals. See #1996. Thanks @clnhlzmn. @@ -527,188 +860,169 @@ Non-breaking changes: suffix specifying the word size such as `i16` or `i32`. - Function `format` now supports more notations: `bin`, 'hex', and `oct`, for example `format(255, {notation: "hex"})`. - - The functions `format`, `bin`, `hex`, `oct` now allow specifying a wordSize, + - The functions `format`, `bin`, `hex`, `oct` now allow specifying a wordSize, like `bin(10, 32)` and `format(10, {notation: "bin", wordSize: 32})`. - - BigNumber support for the bin, hex, and oct literals. + - BigNumber support for the bin, hex, and oct literals. - Extended and improved the example rocket_trajectory_optimization.html. Thanks @Josef37. - # 2020-12-30, version 8.1.1 -- Improved the performance of parsing and evaluating units a lot, see #2065. +- Improved the performance of parsing and evaluating units a lot, see #2065. Thanks @flaviut. -- Upgraded dependency `fraction.js` to `v4.0.13`. -- Moved continuous integration testing from Travis CI to Github Workflow, +- Upgraded dependency `fraction.js` to `v4.0.13`. +- Moved continuous integration testing from Travis CI to Github Workflow, see #2024, #2041. Thanks @harrysarson. - # 2020-12-04, version 8.1.0 - Implemented units `kilogramforce` (`kgf`). Thanks @rnd-debug. -- Fix #2026: Implement a new option `fractionsLimit` for function `simplify`, +- Fix #2026: Implement a new option `fractionsLimit` for function `simplify`, defaulting to `Infinity`. - Improved the documentation of function `clone`. Thanks @redbar0n. - # 2020-11-09, version 8.0.1 - Fix #1979: missing "subset" dependency when using "mathjs/number" entry point. -- Fix #2022: update pretty printing with MathJax example to the latest version +- Fix #2022: update pretty printing with MathJax example to the latest version of MathJax. Thanks @pkra. - # 2020-11-06, version 8.0.0 !!! BE CAREFUL: BREAKING CHANGES !!! -- You can now use mathjs directly in node.js using ES modules without need for - a transpiler (see #1928, #1941, #1962). +- You can now use mathjs directly in node.js using ES modules without need for + a transpiler (see #1928, #1941, #1962). Automatically loading either commonjs code or ES modules code is improved. - All generated code is moved under `/lib`: the browser bundle is moved from - `/dist` to `/lib/browser`, ES module files are moved to `/lib/esm`, + All generated code is moved under `/lib`: the browser bundle is moved from + `/dist` to `/lib/browser`, ES module files are moved to `/lib/esm`, and commonjs files are moved to `/lib/cjs`. Thanks @GreenImp. - Non-minified bundle `dist/math.js` is no longer provided. Either use the minified bundle, or create a bundle yourself. -- Replaced random library `seed-random` with `seedrandom`, see #1955. +- Replaced random library `seed-random` with `seedrandom`, see #1955. Thanks @poppinlp. - Breaking changes in `pickRandom`, see #1990, #1976. - - Will no longer return the input matrix when the given number is greater + - Will no longer return the input matrix when the given number is greater than the length of the provided possibles. Instead, the function always returns results with the requested number of picks. - Will now return a `Matrix` as output when input was a `Matrix`. - Introduced a new syntax: - + ``` math.pickRandom(array, { weights, number, elementWise }) ``` - - Introduced a new option `elementWise`, which is `true` by default. + + - Introduced a new option `elementWise`, which is `true` by default. When setting `elementWise` to false, an array containing arrays will return random pick of arrays instead of the elements inside of the nested arrays. - # 2020-11-02, version 7.6.0 -- Implemented function `rotate(w, theta)`. See #1992, #1160. Thanks @rnd-debug. -- Implemented support for custom characters in Units via `Unit.isValidAlpha`. +- Implemented function `rotate(w, theta)`. See #1992, #1160. Thanks @rnd-debug. +- Implemented support for custom characters in Units via `Unit.isValidAlpha`. See #1663, #2000. Thanks @rnd-debug. - # 2020-10-10, version 7.5.1 - Fix object pollution vulnerability in `math.config`. Thanks Snyk. - # 2020-10-07, version 7.5.0 -- Function `pickRandom` now allows randomly picking elements from matrices +- Function `pickRandom` now allows randomly picking elements from matrices with 2 or more dimensions instead of only from a vector, see #1974. Thanks @KonradLinkowski. - # 2020-10-07, version 7.4.0 -- Implemented support for passing a precision in functions `ceil`, `floor`, +- Implemented support for passing a precision in functions `ceil`, `floor`, and `fix`, similar to `round`, see #1967, #1901. Thanks @rnd-debug. - Implemented function `rotationMatrix`, see #1160, #1984. Thanks @rnd-debug. -- Implement a clear error message when using `sqrtm` with a matrix having +- Implement a clear error message when using `sqrtm` with a matrix having more than two dimensions. Thanks @KonradLinkowski. - Update dependency `decimal.js` to `10.2.1`. - # 2020-09-26, version 7.3.0 - Implemented functions `usolveAll` and `lsolveAll`, see #1916. Thanks @m93a. -- Implemented support for units in functions `std` and `variance`, see #1950. +- Implemented support for units in functions `std` and `variance`, see #1950. Thanks @rnd-debug. -- Implemented support for binary, octal, and hexadecimal notation in the - expression parser, and implemented functions `bin`, `oct`, and `hex` for +- Implemented support for binary, octal, and hexadecimal notation in the + expression parser, and implemented functions `bin`, `oct`, and `hex` for formatting. Thanks @clnhlzmn. -- Fix #1964: inconsistent calculation of negative dividend modulo for +- Fix #1964: inconsistent calculation of negative dividend modulo for `BigNumber` and `Fraction`. Thanks @ovk. - # 2020-08-24, version 7.2.0 -- Implemented new function `diff`, see #1634, #1920. Thanks @Veeloxfire. -- Implemented support for norm 2 for matrices in function `norm`. - Thanks @rnd-debug. - +- Implemented new function `diff`, see #1634, #1920. Thanks @Veeloxfire. +- Implemented support for norm 2 for matrices in function `norm`. + Thanks @rnd-debug. # 2020-07-13, version 7.1.0 -- Implement support for recursion (self-referencing) of typed-functions, - new in `typed-function@2.0.0`. This fixes #1885: functions which where +- Implement support for recursion (self-referencing) of typed-functions, + new in `typed-function@2.0.0`. This fixes #1885: functions which where extended with a new data type did not always work. Thanks @nickewing. -- Fix #1899: documentation on expression trees still using old namespace +- Fix #1899: documentation on expression trees still using old namespace `math.expression.node.*` instead of `math.*`. - # 2020-06-24, version 7.0.2 -- Fix #1882: have `DenseMatrix.resize` and `SparseMatrix.resize` accept +- Fix #1882: have `DenseMatrix.resize` and `SparseMatrix.resize` accept `DenseMatrix` and `SparseMatrix` as inputs too, not only `Array`. - Fix functions `sum`, `prod`, `min`, and `max` not throwing a conversion error when passing a single string, like `sum("abc")`. - # 2020-05-30, version 7.0.1 - Fix #1844: clarify the documentation of function `eigs`. Thanks @Lazersmoke. - Fix #1855: Fix error in the documentation for `math.nthRoots(x)`. - Fix #1856: make the library robust against Object prototype pollution. - # 2020-05-07, version 7.0.0 Breaking changes: -- Improvements in calculation of the `dot` product of complex values. +- Improvements in calculation of the `dot` product of complex values. The first argument is now conjugated. See #1761. Thanks @m93a. - Dropped official support for Node.js v8 which has reached end of life. -- Removed all deprecation warnings introduced in v6. +- Removed all deprecation warnings introduced in v6. To upgrade smoothly from v5 to v7 or higher, upgrade to v6 first and resolve all deprecation warnings. - # 2020-05-04, version 6.6.5 -- Fix #1834: value `Infinity` cannot be serialized and deserialized. - This is solved now with a new `math.replacer` function used as +- Fix #1834: value `Infinity` cannot be serialized and deserialized. + This is solved now with a new `math.replacer` function used as `JSON.stringify(value, math.replacer)`. - Fix #1842: value `Infinity` not turned into the latex symbol `\\infty`. - # 2020-04-15, version 6.6.4 - Fix published files containing Windows line endings (CRLF instead of LF). - # 2020-04-10, version 6.6.3 - Fix #1813: bug in engineering notation for numbers of function `format`, sometimes resulting in needless trailing zeros. -- Fix #1808: methods `.toNumber()` and `.toNumeric()` not working on a +- Fix #1808: methods `.toNumber()` and `.toNumeric()` not working on a unitless unit. - Fix #1645: not being able to use named operators `mod`, `and`, `not`, `or`, `xor`, `to`, `in` as object keys. Thanks @Veeloxfire. - Fix `eigs` not using `config.epsilon`. - # 2020-03-29, version 6.6.2 -- Fix #1789: Function `eigs` not calculating with BigNumber precision +- Fix #1789: Function `eigs` not calculating with BigNumber precision when input contains BigNumbers. - Run the build script during npm `prepare`, so you can use the library directly when installing directly from git. See #1751. Thanks @cinderblock. - # 2020-02-26, version 6.6.1 - Fix #1725: simplify `a/(b/c)`. Thanks @dbramwell. - Fix examples in documentation of `row` and `column`. - # 2020-02-01, version 6.6.0 - Implemented function `eigs`, see #1705, #542 #1175. Thanks @arkajitmandal. @@ -719,32 +1033,27 @@ Breaking changes: - Add a caret to dependencies (like) `^1.2.3`) to allow downstream updates without having to await a new release of mathjs. - # 2020-01-08, version 6.5.0 - Implemented `baseName` option for `createUnit`, see #1707. Thanks @ericman314. - # 2020-01-06, version 6.4.0 - Extended function `dimension` with support for n-dimensional points. Thanks @Veeloxfire. - # 2019-12-31, version 6.3.0 - Improved performance of `factorial` for `BigNumber` up to a factor two, see #1687. Thanks @kmdrGroch. - # 2019-11-20, version 6.2.5 - Fixed `IndexNode` using a hardcoded, one-based implementation of `index`, making it impossible to instantiate a zero-based version of the expression parser. See #782. - # 2019-11-20, version 6.2.4 - Fixed #1669: function 'qr' threw an error if the pivot was zero, @@ -753,7 +1062,6 @@ Breaking changes: - Work around a bug in complex.js where `sign(0)` returns complex NaN. Thanks @harrysarson. - # 2019-10-06, version 6.2.3 - Fixed #1640: function `mean` not working for units. Thanks @clintonc. @@ -761,7 +1069,6 @@ Breaking changes: embedded docs of function `std`. - Improved performance of `isPrime`, see #1641. Thanks @arguiot. - # 2019-09-23, version 6.2.2 - Fixed methods `map` and `clone` not copying the `dotNotation` property of @@ -770,12 +1077,10 @@ Breaking changes: - Fixed #1615: error in the docs of `isNumeric`. - Fixed #1628: Cannot call methods on empty strings or numbers with value `0`. - # 2019-08-31, version 6.2.1 - Fixed #1606: function `format` not working for expressions. - # 2019-08-28, version 6.2.0 - Improved performance of `combinationsWithRep`. Thanks @waseemyusuf. @@ -783,18 +1088,15 @@ Breaking changes: - Fix docs referring to `bit` and `byte` instead of `bits` and `bytes`. - Updated dependency `typed-function@1.1.1`. - # 2019-08-17, version 6.1.0 - Implemented function `combinationsWithRep` (see #1329). Thanks @waseemyusuf. - # 2019-08-05, version 6.0.4 - Fixed #1554, #1565: ES Modules where not transpiled to ES5, giving issues on old browsers. Thanks @mockdeep for helping to find a solution. - # 2019-07-07, version 6.0.3 - Add `unpkg` and `jsdelivr` fields in package.json pointing to UMD build. @@ -802,26 +1104,23 @@ Breaking changes: - Fix #1550: nested user defined function not receiving variables of an outer user defined function. - # 2019-06-11, version 6.0.2 - Fix not being able to set configuration after disabling function `import` (regression since v6.0.0). - # 2019-06-09, version 6.0.1 - Fix function reference not published in npm library. - Fix function `evaluate` and `parse` missing in generated docs. - # 2019-06-08, version 6.0.0 !!! BE CAREFUL: BREAKING CHANGES !!! ### Most notable changes -1. Full support for **ES modules**. Support for tree-shaking out of the box. +1. Full support for **ES modules**. Support for tree-shaking out of the box. Load all functions: @@ -854,14 +1153,13 @@ Breaking changes: }, config) ``` -2. Support for **lightweight, number-only** implementations of all functions: +2. Support for **lightweight, number-only** implementations of all functions: ``` import { add, multiply } from 'mathjs/number' ``` -3. New **dependency injection** solution used under the hood. - +3. New **dependency injection** solution used under the hood. ### Breaking changes @@ -941,32 +1239,27 @@ Breaking changes: and after that rounded the value instead of the other way around. - Fix #1473: remove `'use strict'` in every file, not needed anymore. - # 2019-05-18, version 5.10.3 - Fixed dependency `del` being a dependency instead of devDependency. - # 2019-05-18, version 5.10.2 - Fix #1515, #1516, #1517: broken package due to a naming conflict in the build folder of a util file `typeOf.js` and `typeof.js`. Solved by properly cleaning all build folders before building. - # 2019-05-17, version 5.10.1 - Fix #1512: format using notation `engineering` can give wrong results when the value has less significant digits than the number of digits in the output. - # 2019-05-08, version 5.10.0 - Fix `lib/header.js` not having filled in date and version. Thanks @kevjin. - Upgraded dependency `decimal.js@10.2.0`, fixing an issue on node.js 12. - # 2019-04-08, version 5.9.0 - Implemented functions `row` and `column` (see #1413). Thanks @SzechuanSage. @@ -975,28 +1268,24 @@ Breaking changes: - Fixed #1465: `node.toHTML()` not correct for unary operators like `factorial`. - # 2019-03-20, version 5.8.0 - Implemented new function `apply`. Thanks @bnlcas. - Implemented passing an optional `dimension` argument to `std` and `var`. Thanks @bnlcas. - # 2019-03-10, version 5.7.0 - Implemented support for `pow()` in `derivative`. Thanks @sam-19. - Gracefully handle round-off errors in fix, ceil, floor, and range (Fixes #1429, see also #1434, #1432). Thanks @ericman314. - # 2019-03-02, version 5.6.0 - Upgrade decimal.js to v10.1.1 (#1421). - Fixed #1418: missing whitespace when stringifying an expression containing "not". - # 2019-02-20, version 5.5.0 - Fixed #1401: methods `map` and `forEach` of `SparseMatrix` not working @@ -1004,7 +1293,6 @@ Breaking changes: - Fixed #1404: inconsistent rounding of negative numbers. - Upgrade tiny-emitter to v2.1.0 (#1397). - # 2019-01-25, version 5.4.2 - Fixed `math.format` not working for BigNumbers with a precision above @@ -1013,13 +1301,11 @@ Breaking changes: - Fixed a bug the methods `map`, `forEach`, `traverse`, and `transform` of `FunctionNode`. - # 2019-01-10, version 5.4.1 - Fix #1378: negative bignumbers not formatted correctly. - Upgrade fraction.js to version 4.0.12 (#1369). - # 2018-12-09, version 5.4.0 - Extended sum.js to accept a dimension input to calculate the sum over a @@ -1028,13 +1314,11 @@ Breaking changes: - Remove side effects caused by `Unit.format` and `Unit.toString`, making changes to the unit on execution. Thanks @ericman314. - # 2018-12-03, version 5.3.1 - Fixed #1336: Unit.toSI() returning units with prefix like `mm` instead of `m`. Thanks @ericman314. - # 2018-11-29, version 5.3.0 - Implemented function `hasNumericValue`. Thanks @Sathish-kumar-Subramani. @@ -1042,7 +1326,6 @@ Breaking changes: - Fix #1337: `math.format` not working correctly with `{ precision: 0 }`. Thanks @dkenul. - # 2018-10-30, version 5.2.3 - Fixed #1293: non-unicode characters in `escape-latex` giving issues in some @@ -1051,13 +1334,11 @@ Breaking changes: - Fixed #1304: function `pow` not supporting inputs `pow(Unit, BigNumber)`. - Upgraded dependencies (`escape-latex@1.2.0`) - # 2018-10-23, version 5.2.2 - Fixed #1286: Fixed unit base recognition and formatting for user-defined units. Thanks @ericman314. - # 2018-10-18, version 5.2.1 - Fixed unit `rod` being defined as `5.02921` instead of `5.0292`. @@ -1066,7 +1347,6 @@ Breaking changes: - Upgraded devDependencies (`@babel/core@7.1.2`, `nyc@13.1.0`, `webpack@4.21.0`). - # 2018-10-05, version 5.2.0 - Implemented support for chained conditionals like `10 < x <= 50`. @@ -1076,7 +1356,6 @@ Breaking changes: - Fixed #1240: allow units having just a value and no unit. Thanks @ericman314. - ## 2018-09-09, version 5.1.2 - Fixed a typo in the docs of `parse`. Thanks @mathiasvr. @@ -1088,7 +1367,6 @@ Breaking changes: - Upgraded devDependencies (`babel@7`, `karma-webpack@3.0.4`, `nyc@13.0.1`, `standard@12.0.0`, `uglify-js@3.4.9`, `webpack@4.17.2`) - ## 2018-08-21, version 5.1.1 - Function `isNumeric` now recognizes more types. @@ -1099,7 +1377,6 @@ Breaking changes: - Upgraded dependencies (`escape-latex@1.1.1`) - Upgraded devDependencies (`webpack@4.17.0`) - ## 2018-08-12, version 5.1.0 - Implemented support for strings enclosed in single quotes. @@ -1108,7 +1385,6 @@ Breaking changes: - Implemented new `options` argument in `simplify`. Thanks @paulobuchsbaum. - Bug fixes in `rationalize`, see #1173. Thanks @paulobuchsbaum. - ## 2018-07-22, version 5.0.4 - Strongly improved the performance of functions `factorial` for numbers. @@ -1117,7 +1393,6 @@ Breaking changes: - Strongly improved the performance of function `reshape`, thanks to a friend of @honeybar. - ## 2018-07-14, version 5.0.3 - Fixed many functions (for example `add` and `subtract`) not working @@ -1131,7 +1406,6 @@ Breaking changes: Thanks @harrysarson. - Changed `decimal.js` import to ES6. Thanks @weinshel. - ## 2018-07-07, version 5.0.2 - Fixed #1136: rocket trajectory example broken (since v4.0.0). @@ -1145,16 +1419,14 @@ Breaking changes: Thanks @ChristopherChudzicki. - Fixed a broken link in the documentation on units. Thanks @stropitek. - Upgraded dependencies (`typed-function@1.0.4`, `complex.js@2.0.11`). -- Upgraded devDependencies (`babel-loader@7.1.5 `, `uglify-js@3.4.3`, +- Upgraded devDependencies (`babel-loader@7.1.5`, `uglify-js@3.4.3`, `expr-eval@1.2.2`, `webpack@4.15.1`). - ## 2018-07-01, version 5.0.1 - Improved error messaging when converting units. Thanks @gap777. - Upgraded devDependencies (`kerma`, `uglify-js`, `webpack`). - ## 2018-06-16, version 5.0.0 !!! BE CAREFUL: BREAKING CHANGES !!! @@ -1171,7 +1443,7 @@ Breaking changes: - Upgraded dependencies: - `decimal.js` from `9.0.1` to `10.0.1` - Upgraded dev dependencies -- Changed code style to https://standardjs.com/, run linter on `npm test`. +- Changed code style to , run linter on `npm test`. See #1110. - Dropped support for bower. Use npm or an other package manages instead. - Dropped support for (non-primitive) instances of `Number`, `Boolean`, and @@ -1182,7 +1454,6 @@ Breaking changes: - Fixed #1103: Calling `toTex` on node that contains `derivative` causing an exception. Thanks @joelhoover. - ## 2018-06-02, version 4.4.2 - Drastically improved the performance of `det`. Thanks @ericman314. @@ -1191,18 +1462,15 @@ Breaking changes: - Fixed #1122 a regression in function `inv` (since `v4.4.1`). Thanks @ericman314. - ## 2018-05-29, version 4.4.1 - Fixed #1109: a bug in `inv` when dealing with values close to zero. Thanks @ericman314. - ## 2018-05-28, version 4.4.0 - Implemented functions `equalText` and `compareText`. See #1085. - ## 2018-05-21, version 4.3.0 - Implemented matrix exponential `math.expm`. Thanks @ericman314. @@ -1212,7 +1480,6 @@ Breaking changes: - `fraction.js` from `v4.0.4` to `v4.0.8`. - Upgraded devDependencies (`mocha`, `uglify-js`, `webpack`). - ## 2018-05-05, version 4.2.2 - Fixed calculating the Frobenius norm of complex matrices correctly, @@ -1220,12 +1487,10 @@ Breaking changes: - Fixed #1076: cannot use mathjs in React VR by updating to `escape-latex@1.0.3`. - ## 2018-05-02, version 4.2.1 - Fixed `dist/math.js` being minified. - ## 2018-05-02, version 4.2.0 - Implemented function `math.sqrtm`. Thanks @ferrolho. @@ -1235,7 +1500,6 @@ Breaking changes: - Upgraded development dependencies. - Dropped integration testing on nodejs v4. - ## 2018-04-18, version 4.1.2 - Fixed #1082: implemented support for unit plurals `decades`, `centuries`, @@ -1243,13 +1507,11 @@ Breaking changes: - Fixed #1083: units `decade` and `watt` having a wrong name when stringifying. Thanks @ericman314. - ## 2018-04-11, version 4.1.1 - Fixed #1063: derivative not working when resolving a variable with unary minus like `math.derivative('-x', 'x')`. - ## 2018-04-08, version 4.1.0 - Extended function `math.print` with support for arrays and matrices. @@ -1261,13 +1523,11 @@ Breaking changes: - Fixed #1072: Added support for long and short prefixes for the unit `bar` (i.e. `millibar` and `mbar`). - ## 2018-03-17, version 4.0.1 - Fixed #1062: mathjs not working on ES5 browsers like IE11 and Safari 9.3. - Fixed #1061: `math.unit` not accepting input like `1/s`. - ## 2018-02-25, version 4.0.0 !!! BE CAREFUL: BREAKING CHANGES !!! @@ -1279,52 +1539,55 @@ Breaking changes (see also #682): The compiler of the expression parser is replaced with one that doesn't use `eval` internally. See #1019. This means: - - a slightly improved performance on most browsers. - - less risk of security exploits. - - the code of the new compiler is easier to understand, maintain, and debug. + - a slightly improved performance on most browsers. + - less risk of security exploits. + - the code of the new compiler is easier to understand, maintain, and debug. Breaking change here: When using custom nodes in the expression parser, the syntax of `_compile` has changed. This is an undocumented feature though. - **Parsed expressions** - - The class `ConstantNode` is changed such that it just holds a value + - The class `ConstantNode` is changed such that it just holds a value instead of holding a stringified value and it's type. `ConstantNode(valueStr, valueType`) is now `ConstantNode(value)` Stringification uses `math.format`, which may result in differently formatted numeric output. - - The constants `true`, `false`, `null`, `undefined`, `NaN`, `Infinity`, + - The constants `true`, `false`, `null`, `undefined`, `NaN`, `Infinity`, and `uninitialized` are now parsed as ConstantNodes instead of SymbolNodes in the expression parser. See #833. - **Implicit multiplication** - - Changed the behavior of implicit multiplication to have higher + - Changed the behavior of implicit multiplication to have higher precedence than explicit multiplication and division, except in a number of specific cases. This gives a more natural behavior for implicit multiplications. For example `24h / 6h` now returns `4`, whilst `1/2 kg` evaluates to `0.5 kg`. Thanks @ericman314. See: #792. - Detailed documentation: https://github.com/josdejong/mathjs/blob/v4/docs/expressions/syntax.md#implicit-multiplication. + Detailed documentation: . - - Immediately invoking a function returned by a function like `partialAdd(2)(3)` + - Immediately invoking a function returned by a function like `partialAdd(2)(3)` is no longer supported, instead these expressions are evaluated as an implicit multiplication `partialAdd(2) * (3)`. See #1035. - **String formatting** - - In function `math.format`, the options `{exponential: {lower: number, upper: number}}` + - In function `math.format`, the options `{exponential: {lower: number, upper: number}}` (where `lower` and `upper` are values) are replaced with `{lowerExp: number, upperExp: number}` (where `lowerExp` and `upperExp` are exponents). See #676. For example: + ```js math.format(2000, {exponential: {lower: 1e-2, upper: 1e2}}) ``` + is now: + ```js math.format(2000, {lowerExp: -2, upperExp: 2}) ``` - - In function `math.format`, the option `notation: 'fixed'` no longer rounds to + - In function `math.format`, the option `notation: 'fixed'` no longer rounds to zero digits when no precision is specified: it leaves the digits as is. See #676. @@ -1345,17 +1608,17 @@ Breaking changes (see also #682): - **Null** - - `null` is no longer implicitly casted to a number `0`, so input like + - `null` is no longer implicitly casted to a number `0`, so input like `math.add(2, null)` is no longer supported. See #830, #353. - - Dropped constant `uninitialized`, which was used to initialize + - Dropped constant `uninitialized`, which was used to initialize leave new entries undefined when resizing a matrix is removed. Use `undefined` instead to indicate entries that are not explicitly set. See #833. - **New typed-function library** - - The `typed-function` library used to check the input types + - The `typed-function` library used to check the input types of functions is completely rewritten and doesn't use `eval` under the hood anymore. This means a reduced security risk, and easier to debug code. The API is the same, but error messages may differ @@ -1375,7 +1638,6 @@ Non breaking changes: - Fixed #1014: `derivative` silently dropping additional arguments from operator nodes with more than two arguments. - ## 2018-02-07, version 3.20.2 - Upgraded to `typed-function@0.10.7` (bug-fix release). @@ -1384,19 +1646,17 @@ Non breaking changes: - Fixed #995: spaces and underscores not property being escaped in `toTex()`. Thanks @FSMaxB. - ## 2018-01-17, version 3.20.1 - Fixed #1018: `simplifyCore` failing in some cases with parentheses. Thanks @firepick1. - ## 2018-01-14, version 3.20.0 - Implement support for 3 or more arguments for operators `+` and `*` in `derivative`. Thanks @HarrySarson. See #1002. - Fixed `simplify` evalution of `simplify` of functions with more than two - arguments wrongly: `simplify('f(x, y, z)') evaluated to `f(f(x, y), z)` + arguments wrongly: `simplify('f(x, y, z)') evaluated to`f(f(x, y), z)` instead of `f(x, y, z)`. Thanks @joelhoover. - Fixed `simplify` throwing an error in some cases when simplifying unknown functions, for example `simplify('f(4)')`. Thanks @joelhoover. @@ -1404,7 +1664,6 @@ Non breaking changes: minus, like `0 - -x`. Thanks @joelhoover. - Fixed an error in an example in the documentation of `xor`. Thanks @denisx. - ## 2018-01-06, version 3.19.0 - Extended functions `distance` and `intersect` with support for BigNumbers. @@ -1412,22 +1671,22 @@ Non breaking changes: - Improvements in function `simplify`: added a rule that allows combining of like terms in embedded quantities. Thanks @joelhoover. - ## 2017-12-28, version 3.18.1 - Fixed #998: An issue with simplifying an expression containing a subtraction. Thanks @firepick1. - ## 2017-12-16, version 3.18.0 - Implemented function `rationalize`. Thanks @paulobuchsbaum. - Upgraded dependencies: + ``` decimal.js 7.2.3 → 9.0.1 (no breaking changes affecting mathjs) fraction.js 4.0.2 → 4.0.4 tiny-emitter 2.0.0 → 2.0.2 ``` + - Upgraded dev dependencies. - Fixed #975: a wrong example in the docs of lusolve. - Fixed #983: `pickRandom` returning an array instead of single value @@ -1435,7 +1694,6 @@ Non breaking changes: - Fixed #969: preven issues with yarn autoclean by renaming an interally used folder "docs" to "embeddedDocs". - ## 2017-11-18, version 3.17.0 - Improved `simplify` for nested exponentiations. Thanks @IvanVergiliev. @@ -1446,20 +1704,17 @@ Non breaking changes: replaced by using unicode characters when creating an object. No known exploit, but could possibly allow arbitrary code execution. Thanks Masato Kinugawa. - ## 2017-10-18, version 3.16.5 - Fixed #954: Functions `add` and `multiply` not working when passing three or more arrays or matrices. - ## 2017-10-01, version 3.16.4 - Fixed #948, #949: function `simplify` returning wrong results or running into an infinite recursive loop. Thanks @ericman314. - Fixed many small issues in the embedded docs. Thanks @Schnark. - ## 2017-08-28, version 3.16.3 - Fixed #934: Wrong simplification of unary minus. Thanks @firepick1. @@ -1468,7 +1723,6 @@ Non breaking changes: numbers having just one of their parts (re/im) being `NaN`. - Fixed #929: `FibonacciHeap.isEmpty` returning wrong result. - ## 2017-08-20, version 3.16.2 - Fixed #924: a regression in `simplify` not accepting the signature @@ -1476,7 +1730,6 @@ Non breaking changes: - Fixed missing parenthesis when stringifying expressions containing implicit multiplications (see #922). Thanks @FSMaxB. - ## 2017-08-12, version 3.16.1 - For security reasons, type checking is now done in a more strict @@ -1489,7 +1742,6 @@ Non breaking changes: immediately invoked function assignment not being wrapped in parenthesis (for example `(f(x) = x^2)(4)`). - ## 2017-08-06, version 3.16.0 - Significant performance improvements in `math.simplify`. @@ -1499,7 +1751,6 @@ Non breaking changes: - Fixed #912: math.js didn't work on IE10 anymore (regression since 3.15.0). - ## 2017-07-29, version 3.15.0 - Added support for the dollar character `$` in symbol names (see #895). @@ -1514,19 +1765,16 @@ Non breaking changes: and `forEach`. - Index and original array/matrix not passed in `map` and `filter`. - ## 2017-07-05, version 3.14.2 - Upgraded to `fraction.js@4.0.2` - Fixed #891 using BigNumbers not working in browser environments. - ## 2017-06-30, version 3.14.1 - Reverted to `fraction.js@4.0.0`, there is an issue with `4.0.1` in the browser. - ## 2017-06-30, version 3.14.0 - Implemented set methods `setCartesian`, `setDifference`, @@ -1546,14 +1794,12 @@ Non breaking changes: - More informative error message when using single quotes instead of double quotes around a string. Thanks @HarrySarson. - ## 2017-05-27, version 3.13.3 - Fixed a bug in function `intersection` of line and plane. Thanks @viclai. - Fixed security vulnerabilities. - ## 2017-05-26, version 3.13.2 - Disabled function `chain` inside the expression parser for security @@ -1562,14 +1808,12 @@ Non breaking changes: from Arrays correctly. (like `math.eval('arr[1]', {arr: [math.bignumber(2)]})`. - Fixed #861: physical constants not available in the expression parser. - ## 2017-05-12, version 3.13.1 - Fixed creating units with an alias not working within the expression parser. - Fixed security vulnerabilities. Thanks Sam. - ## 2017-05-12, version 3.13.0 - Command line application can now evaluate inline expressions @@ -1582,17 +1826,14 @@ Non breaking changes: - Fixed #838: Function `simplify` now supports constants like `e`. Thanks @tetslee. - ## 2017-05-05, version 3.12.3 - Fixed security vulnerabilities. Thanks Dan and Sam. - ## 2017-04-30, version 3.12.2 - Added a rocket trajectory optimization example. - ## 2017-04-24, version 3.12.1 - Fixed #804 @@ -1601,13 +1842,11 @@ Non breaking changes: - Fixed security vulnerabilities in the expression parser. Thanks Sam and Dan. - ## 2017-04-17, version 3.12.0 - Implemented QR decomposition, function `math.qr`. Thanks @HarrySarson. - Fixed #824: Calling `math.random()` freezes IE and node.js. - ## 2017-04-08, version 3.11.5 - More security measures in the expression parser. @@ -1617,28 +1856,23 @@ Non breaking changes: objects, not on classes, arrays, and functions anymore. - Accessing methods is restricted to a set of known, safe methods. - ## 2017-04-03, version 3.11.4 - Fixed a security vulnerability in the expression parser. Thanks @xfix. - ## 2017-04-03, version 3.11.3 - Fixed a security vulnerability in the expression parser. Thanks @xfix. - ## 2017-04-03, version 3.11.2 - Fixed a security vulnerability in the expression parser. Thanks @xfix. - ## 2017-04-02, version 3.11.1 - Fixed security vulnerabilities in the expression parser. Thanks Joe Vennix and @xfix. - ## 2017-04-02, version 3.11.0 - Implemented method Unit.toSI() to convert a unit to base SI units. @@ -1646,25 +1880,21 @@ Non breaking changes: - Fixed #821, #822: security vulnerabilities in the expression parser. Thanks @comex and @xfix. - ## 2017-03-31, version 3.10.3 - More security fixes related to the ones fixed in `v3.10.2`. - ## 2017-03-31, version 3.10.2 - Fixed a security vulnerability in the expression parser allowing execution of arbitrary JavaScript. Thanks @CapacitorSet and @denvit. - ## 2017-03-26, version 3.10.1 - Fixed `xgcd` for negative values. Thanks @litmit. - Fixed #807: function transform of existing functions not being removed when overriding such a function. - ## 2017-03-05, version 3.10.0 - Implemented function `reshape`. Thanks @patgrasso and @ericman314. @@ -1674,19 +1904,16 @@ Non breaking changes: - Dropped support for component package manager (which became deprecated about one and a half year ago). - ## 2017-02-22, version 3.9.3 - Fixed #797: issue with production builds of React Native projects. - Fixed `math.round` not accepting inputs `NaN`, `Infinity`, `-Infinity`. - Upgraded all dependencies. - ## 2017-02-16, version 3.9.2 - Fixed #795: Parse error in case of a multi-line expression with just comments. - ## 2017-02-06, version 3.9.1 - Fixed #789: Math.js not supporting conversion of `string` to `BigNumber`, @@ -1695,7 +1922,6 @@ Non breaking changes: functions via `scope` to functions having `rawArgs = true`. - Small fixes in the docs. Thanks @HarrySarson. - ## 2017-01-23, version 3.9.0 - Implemented support for algebra: powerful new functions `simplify` and @@ -1705,14 +1931,12 @@ Non breaking changes: - Fixed #765: `FunctionAssignmentNode.toString()` returning a string incompatible with the function assignment syntax. - ## 2016-12-15, version 3.8.1 - Implemented function `mad` (median absolute deviation). Thanks @ruhleder. - Fixed #762: expression parser failing to invoke a function returned by a function. - ## 2016-11-18, version 3.8.0 - Functions `add` and `multiply` now accept more than two arguments. See #739. @@ -1727,7 +1951,6 @@ Non breaking changes: - Fixed #749: Units `rad`, `deg`, and `grad` can now have prefixes like `millirad`. - Some fixes in the docs and comments of examples. Thanks @HarrySarson. - ## 2016-11-05, version 3.7.0 - Implemented method `Node.equals(other)` for all nodes of the expression parser. @@ -1736,7 +1959,6 @@ Non breaking changes: - Implicit conversions between Fractions and BigNumbers throw a neat error now (See #710). - ## 2016-10-21, version 3.6.0 - Implemented function `erf()`. THanks @patgrasso. @@ -1750,23 +1972,19 @@ Non breaking changes: like `-2 2` and `2^3 4` (right after the second value of an operator). - Fixed #688: Describe allowed variable names in the docs. - ## 2016-09-21, version 3.5.3 - Some more fixes regarding numbers ending with a decimal mark (like `2.`). - ## 2016-09-20, version 3.5.2 - Fixed numbers ending with a decimal mark (like `2.`) not being supported by the parser, solved the underlying ambiguity in the parser. See #707, #711. - ## 2016-09-12, version 3.5.1 - Removed a left over console.log statement. Thanks @eknkc. - ## 2016-09-07, version 3.5.0 - Comments of expressions are are now stored in the parsed nodes. See #690. @@ -1775,20 +1993,17 @@ Non breaking changes: - Fixed #707: The expression parser no longer accepts numbers ending with a dot like `2.`. - ## 2016-08-08, version 3.4.1 - Fixed broken bundle files (`dist/math.js`, `dist/math.min.js`). - Fixed some layout issues in the function reference docs. - ## 2016-08-07, version 3.4.0 - Implemented support for custom units using `createUnit`. Thanks @ericman314. - Implemented function `splitUnits`. Thanks @ericman314. - Implemented function `isPrime`. Thanks @MathBunny. - ## 2016-07-05, version 3.3.0 - Implemented function `isNaN`. @@ -1799,13 +2014,11 @@ Non breaking changes: - Fixed #665: functions `map`, `forEach`, and `filter` now invoke callbacks which are a typed-function with the correct number of arguments. - ## 2016-04-26, version 3.2.1 - Fixed #651: unable to perform calculations on "Unit-less" units. - Fixed matrix.subset mutating the replacement matrix when unsqueezing it. - ## 2016-04-16, version 3.2.0 - Implemented #644: method `Parser.getAll()` to retrieve all defined variables. @@ -1819,7 +2032,6 @@ Non breaking changes: - Fixed #645: Added documentation about `engineering` notation of function `math.format`. - ## 2016-04-03, version 3.1.4 - Using ES6 Math functions like `Math.sinh`, `Math.cbrt`, `Math.sign`, etc when @@ -1833,17 +2045,14 @@ Non breaking changes: - Fixed #625: Unit `in` (`inch`) not always working due to ambiguity with the operator `a in b` (alias of `a to b`). - ## 2016-03-24, version 3.1.3 - Fix broken bundle. - ## 2016-03-24, version 3.1.2 - Fix broken npm release. - ## 2016-03-24, version 3.1.1 - Fixed #621: a bug in parsing implicit multiplications like `(2)(3)+4`. @@ -1852,7 +2061,6 @@ Non breaking changes: - Throw an error when functions `min`, `max`, `mean`, or `median` are invoked with multiple matrices as arguments (see #598). - ## 2016-03-19, version 3.1.0 - Hide multiplication operator by default when outputting `toTex` and `toString` @@ -1864,7 +2072,6 @@ Non breaking changes: - Added automatic conversions from `boolean` and `null` to `Fraction`, and conversions from `Fraction` to `Complex`. - ## 2016-03-04, version 3.0.0 ### breaking changes @@ -1927,7 +2134,6 @@ Non breaking changes: - Fixed angle units `deg`, `rad`, `grad`, `cycle`, `arcsec`, and `arcmin` not being defined as BigNumbers when configuring to use BigNumbers. - ## 2016-02-03, version 2.7.0 - Added more unit aliases for time: `secs`, `mins`, `hr`, `hrs`. See #551. @@ -1936,7 +2142,6 @@ Non breaking changes: - Fixed #546: Cannot import BigNumber, Fraction, Matrix, Array. Thanks @brettjurgens. - ## 2016-01-08, version 2.6.0 - Implemented (complex) units `VA` and `VAR`. @@ -1948,7 +2153,6 @@ Non breaking changes: of the correct subset. - Fixed #536: A bug in an internal method used for sparse matrices. - ## 2015-12-05, version 2.5.0 - Implemented support for numeric types `Fraction` and `BigNumber` in units. @@ -1960,14 +2164,12 @@ Non breaking changes: function definition. - Fixed: Function `number` didn't support `Fraction` as input. - ## 2015-11-14, version 2.4.2 - Fixed #502: Issue with `format` in some JavaScript engines. - Fixed #503: Removed trailing commas and the use of keyword `import` as property, as this gives issues with old JavaScript engines. - ## 2015-10-29, version 2.4.1 - Fixed #480: `nthRoot` not working on Internet Explorer (up to IE11). @@ -1984,7 +2186,6 @@ Non breaking changes: - Fixed: removed memoization from `gamma` and `factorial` functions, this could blow up memory. - ## 2015-10-09, version 2.4.0 - Added support in the expression parser for mathematical alphanumeric symbols @@ -1995,7 +2196,6 @@ Non breaking changes: BigNumber integer values around multiples of tau (i.e. `sin(bignumber(7))`). - Fixed value of unit `stone`. Thanks @Esvandiary for finding the error. - ## 2015-09-19, version 2.3.0 - Implemented function `distance`. Thanks @devanp92. @@ -2007,7 +2207,6 @@ Non breaking changes: - Fixed #463, #322: inconsistent handling of implicit multiplication. - Fixed #444: factorial of infinity not returning infinity. - ## 2015-08-30, version 2.2.0 - Units with powers (like `m^2` and `s^-1`) now output with the best prefix. @@ -2019,13 +2218,11 @@ Non breaking changes: - Fixed function `to` not working in case of a simplified unit. - Fixed #437: an issue with row swapping in `lup`, also affecting `lusolve`. - ## 2015-08-12, version 2.1.1 - Fixed wrong values of the physical constants `speedOfLight`, `molarMassC12`, and `magneticFluxQuantum`. Thanks @ericman314 for finding two of them. - ## 2015-08-11, version 2.1.0 - Implemented derived units (like `110 km/h in m/s`). Thanks @ericman314. @@ -2039,13 +2236,11 @@ Non breaking changes: - Internal functions `Unit.parse` and `Complex.parse` now throw an Error instead of returning null when passing invalid input. - ## 2015-07-29, version 2.0.1 - Fixed operations with mixed fractions and numbers be converted to numbers instead of fractions. - ## 2015-07-28, version 2.0.0 - Large internal refactoring: @@ -2085,7 +2280,6 @@ Non breaking changes: - The size of Arrays is no longer validated. Matrices will validate this on creation. - ## 2015-07-12, version 1.7.1 - Fixed #397: Inaccuracies in nthRoot for very large values, and wrong results @@ -2093,7 +2287,6 @@ Non breaking changes: - Fixed #405: Parser throws error when defining a function in a multiline expression. - ## 2015-05-31, version 1.7.0 - Implemented function `quantileSeq` and `partitionSelect`. Thanks @BigFav. @@ -2108,14 +2301,12 @@ Non breaking changes: node tree (see #349). - Fixed #381: issue in docs of `randomInt`. - ## 2015-04-22, version 1.6.0 - Improvements in `toTex`. Thanks @FSMaxB. - Fixed #328: `abs(0 + 0i)` evaluated to `NaN`. - Fixed not being able to override lazy loaded constants. - ## 2015-04-09, version 1.5.2 - Fixed #313: parsed functions did not handle recursive calls correctly. @@ -2123,13 +2314,11 @@ Non breaking changes: following SI standards (`1 KiB == 1024 B`, `1 kB == 1000 B`). - Performance improvements in parsed functions. - ## 2015-04-08, version 1.5.1 - Fixed #316: a bug in rounding values when formatting. - Fixed #317, #319: a bug in formatting negative values. - ## 2015-03-28, version 1.5.0 - Added unit `stone` (6.35 kg). @@ -2141,7 +2330,6 @@ Non breaking changes: - Fixed #291: function `format` sometimes returning exponential notation when it should return a fixed notation. - ## 2015-02-28, version 1.4.0 - Implemented trigonometric functions: @@ -2156,7 +2344,6 @@ Non breaking changes: - Fixed #281: improved formatting complex numbers. Round the real or imaginary part to zero when the difference is larger than the configured precision. - ## 2015-02-09, version 1.3.0 - Implemented BigNumber implementations of most trigonometric functions: `sin`, @@ -2170,7 +2357,6 @@ Non breaking changes: `permutations`. - Some minor fixes in the docs. Thanks @KenanY. - ## 2014-12-25, version 1.2.0 - Support for bitwise operations `bitAnd`, `bitNot`, `bitOr`, `bitXor`, @@ -2184,14 +2370,12 @@ Non breaking changes: functional until math.js v2.0. - Upgraded to decimal.js v4.0.1 (BigNumber library). - ## 2014-11-22, version 1.1.1 - Fixed Unit divided by Number returning zero. - Fixed BigNumber downgrading to Number for a negative base in `pow`. - Fixed some typos in error messaging (thanks @andy0130tw) and docs. - ## 2014-11-15, version 1.1.0 - Implemented functions `dot` (dot product), `cross` (cross product), and @@ -2212,7 +2396,6 @@ Non breaking changes: of via a function `add`. - Fixed `2e` giving a syntax error instead of being parsed as `2 * e`. - ## 2014-09-12, version 1.0.1 - Disabled array notation for ranges in a matrix index in the expression parser @@ -2221,7 +2404,6 @@ Non breaking changes: a scalar. - Fixed some missing docs and broken links in the docs. - ## 2014-09-04, version 1.0.0 - Implemented a function `filter(x, test)`. @@ -2231,7 +2413,6 @@ Non breaking changes: - Fixed an zero-based issue when getting a matrix subset using an index containing a matrix. - ## 2014-08-21, version 0.27.0 - Implemented functions `sort(x [, compare])` and `flatten(x)`. @@ -2250,7 +2431,6 @@ Non breaking changes: - A returned matrix subset is now only squeezed when the `index` consists of scalar values, and no longer for ranges resolving into a single value. - ## 2014-08-03, version 0.26.0 - A new instance of math.js can no longer be created like `math([options])`, @@ -2280,7 +2460,6 @@ Non breaking changes: - Fixed broken auto completion in CLI. - Some minor fixes. - ## 2014-07-01, version 0.25.0 - The library now immediately returns a default instance of mathjs, there is @@ -2303,12 +2482,10 @@ Non breaking changes: like `math.eval('10 * celsius')`. - Fixed a bug with symbols having value `undefined` not being evaluated. - ## 2014-06-20, version 0.24.1 - Something went wrong with publishing on npm. - ## 2014-06-20, version 0.24.0 - Added constant `null`. @@ -2322,7 +2499,6 @@ Non breaking changes: - Fixed imported, wrapped functions not accepting `null` and `undefined` as function arguments. - ## 2014-06-10, version 0.23.0 - Renamed some functions (everything now has a logical, camel case name): @@ -2354,7 +2530,6 @@ Non breaking changes: return ans; } - ## 2014-05-22, version 0.22.0 - Implemented support to export expressions to LaTeX. Thanks Niels Heisterkamp @@ -2367,7 +2542,6 @@ Non breaking changes: - Fixed random functions not accepting Matrix as input, and always returning a Matrix as output. - ## 2014-05-13, version 0.21.1 - Removed `crypto` library from the bundle. @@ -2377,7 +2551,6 @@ Non breaking changes: - Fixed parser not being able to evaluate an exponent followed by a unary minus like `2^-3`, and a transpose followed by an index like `[3]'[1]`. - ## 2014-04-24, version 0.21.0 - Implemented trigonometric hyperbolic functions `cosh`, `coth`, `csch`, @@ -2386,7 +2559,6 @@ Non breaking changes: - Fixed functions `log`, `log10`, `pow`, and `sqrt` not supporting complex results from BigNumber input (like `sqrt(bignumber(-4))`). - ## 2014-04-16, version 0.20.0 - Switched to module `decimal.js` for BigNumber support, instead of @@ -2410,14 +2582,12 @@ Non breaking changes: of zero-based. - Minor bug fixes. - ## 2014-03-30, version 0.19.0 - Implemented functions `compare`, `sum`, `prod`, `var`, `std`, `median`. - Implemented function `ifElse` Thanks @mtraynham. - Minor bug fixes. - ## 2014-02-15, version 0.18.1 - Added unit `feet`. @@ -2427,7 +2597,6 @@ Non breaking changes: - Fixed an error in function `combinations` for large numbers, and improved performance of both functions `combinations` and `permutations`. - ## 2014-01-18, version 0.18.0 - Changed matrix index notation of expression parser from round brackets to @@ -2446,13 +2615,11 @@ Non breaking changes: Thanks Daniel Levin (@daniel-levin). - Added lower case abbreviation `l` for unit litre. - ## 2013-12-19, version 0.17.1 - Fixed a bug with negative temperatures. - Fixed a bug with prefixes of units squared meter `m2` and cubic meter `m3`. - ## 2013-12-12, version 0.17.0 - Renamed and flattened configuration settings: @@ -2464,7 +2631,6 @@ Non breaking changes: - Fixed support for old browsers (IE8 and older), compatible when using es5-shim. - Fixed support for Java's ScriptEngine. - ## 2013-11-28, version 0.16.0 - Implemented BigNumber support for arbitrary precision calculations. @@ -2496,7 +2662,6 @@ Non breaking changes: input. - Minor bug fixes. - ## 2013-10-26, version 0.15.0 - Math.js must be instantiated now, static calls are no longer supported. Usage: @@ -2528,7 +2693,6 @@ Non breaking changes: - Removed support for comparing complex numbers in functions `smaller`, `smallereq`, `larger`, `largereq`. Complex numbers cannot be ordered. - ## 2013-10-08, version 0.14.0 - Introduced an option `math.options.matrix.default` which can have values @@ -2545,7 +2709,6 @@ Non breaking changes: - Documentation is restructured and extended. - Fixed non working operator `mod` (modulus operator). - ## 2013-09-03, version 0.13.0 - Implemented support for booleans in all relevant functions. @@ -2568,13 +2731,11 @@ Non breaking changes: - Moved `math.expr.Selector` to `math.chaining.Selector`. - Fixed some edge cases in functions `lcm` and `xgcd`. - ## 2013-08-22, version 0.12.1 - Fixed outdated version of README.md. - Fixed a broken unit test. - ## 2013-08-22, version 0.12.0 - Implemented functions `random([min, max])`, `randomInt([min, max])`, @@ -2598,12 +2759,10 @@ Non breaking changes: value with an imaginary part equal to zero to a number. - Fixed zeros being formatted as null. Thanks @TimKraft. - ## 2013-07-23, version 0.11.1 - Fixed missing development dependency - ## 2013-07-23, version 0.11.0 - Changed math.js from one-based to zero-based indexes. @@ -2618,7 +2777,6 @@ Non breaking changes: - Fixed not accepting empty matrices like `[[], []]`. - Some fixes in the end user documentation. - ## 2013-07-08, version 0.10.0 - For complex calculations, all functions now automatically replace results @@ -2633,7 +2791,6 @@ Non breaking changes: - Renamed function `unaryminus` to `unary`. - Fixed a bug in determining node dependencies in function assignments. - ## 2013-06-14, version 0.9.1 - Implemented element-wise functions and operators: `emultiply` (`x .* y`), @@ -2645,7 +2802,6 @@ Non breaking changes: - Fixed a bug in function multiply multiplying a pure complex value with Infinity. - ## 2013-05-29, version 0.9.0 - Implemented function `math.parse(expr [,scope])`. Optional parameter scope can @@ -2663,7 +2819,6 @@ Non breaking changes: - Fixed function mod for negative numerators, and added error messages in case of wrong input. - ## 2013-05-18, version 0.8.2 - Extended the import function and some other minor improvements. @@ -2671,12 +2826,10 @@ Non breaking changes: - Fixed a bug in function subtract, when subtracting a complex number from a real number. - ## 2013-05-10, version 0.8.1 - Fixed an npm warning when installing mathjs globally. - ## 2013-05-10, version 0.8.0 - Implemented a command line interface. When math.js is installed globally via @@ -2692,13 +2845,11 @@ Non breaking changes: - Fixed a bug in updating a subset of a non-existing variable. - Minor bug fixes. - ## 2013-05-04, version 0.7.2 - Fixed method unequal, which was checking for equality instead of inequality. Thanks @FJS2. - ## 2013-04-27, version 0.7.1 - Improvements in the parser: @@ -2714,7 +2865,6 @@ Non breaking changes: - Fixed a bug in Workspace.insertAfter. - Fixed: math.js now works on IE 6-8 too. - ## 2013-04-20, version 0.7.0 - Implemented method `math.eval`, which uses a readonly parser to evaluate @@ -2731,7 +2881,6 @@ Non breaking changes: - Fixed method math.typeof on IE. - Minor bug fixes and improvements. - ## 2013-04-13, version 0.6.0 - Implemented chained operations via method math.select(). For example @@ -2753,7 +2902,6 @@ Non breaking changes: - Fixed constant i being defined as -1i instead of 1i. - Minor bug fixes. - ## 2013-04-06, version 0.5.0 - Implemented data types Matrix and Range. @@ -2774,7 +2922,6 @@ Non breaking changes: - Changed: renamed the parsers method 'put' into 'set'. - Fixed: method 'in' did not check for units to have the same base. - ## 2013-03-16, version 0.4.0 - Implemented Array support for all methods. @@ -2787,14 +2934,12 @@ Non breaking changes: - Fixed: method 'typeof' was not working well with minified and mangled code. - Fixed: errors in determining the best prefix for a unit. - ## 2013-03-09, version 0.3.0 - Implemented Workspace - Implemented methods cot, csc, sec. - Implemented Array support for methods with one parameter. - ## 2013-02-25, version 0.2.0 - Parser, Scope, and expression tree with Nodes implemented. @@ -2802,21 +2947,18 @@ Non breaking changes: - Implemented methods arg, conj, cube, equal, factorial, im, largereq, log(x, base), log10, mod, re, sign, smallereq, square, unequal. - ## 2013-02-18, version 0.1.0 - Reached full compatibility with Javascripts built-in Math library. - More functions implemented. - Some bugfixes. - ## 2013-02-16, version 0.0.2 - All constants of Math implemented, plus the imaginary unit i. - Data types Complex and Unit implemented. - First set of functions implemented. - ## 2013-02-15, version 0.0.1 - First publish of the mathjs package. (package is still empty) diff --git a/NOTICE b/NOTICE index 1f8830bc15..8aa6f0d286 100644 --- a/NOTICE +++ b/NOTICE @@ -1,7 +1,7 @@ math.js https://github.com/josdejong/mathjs -Copyright (C) 2013-2023 Jos de Jong +Copyright (C) 2013-2024 Jos de Jong Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/README.md b/README.md index 972520384c..5300f6bfff 100644 --- a/README.md +++ b/README.md @@ -7,41 +7,16 @@ Math.js is an extensive math library for JavaScript and Node.js. It features a f [![Version](https://img.shields.io/npm/v/mathjs.svg)](https://www.npmjs.com/package/mathjs) [![Downloads](https://img.shields.io/npm/dm/mathjs.svg)](https://www.npmjs.com/package/mathjs) [![Build Status](https://github.com/josdejong/mathjs/workflows/Node.js%20CI/badge.svg)](https://github.com/josdejong/mathjs/actions) -[![Maintenance](https://img.shields.io/maintenance/yes/2023.svg)](https://github.com/josdejong/mathjs/graphs/commit-activity) +[![Maintenance](https://img.shields.io/maintenance/yes/2024.svg)](https://github.com/josdejong/mathjs/graphs/commit-activity) [![License](https://img.shields.io/github/license/josdejong/mathjs.svg)](https://github.com/josdejong/mathjs/blob/master/LICENSE) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fjosdejong%2Fmathjs.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fjosdejong%2Fmathjs?ref=badge_shield) [![Codecov](https://codecov.io/gh/josdejong/mathjs/branch/develop/graph/badge.svg)](https://codecov.io/gh/josdejong/mathjs) -[![Foresight](https://api-public.service.runforesight.com/api/v1/badge/test?repoId=13cb22bf-6cd5-4c4b-a9de-46081ac63ffb)](https://mathjs.app.runforesight.com/) -[![Github Sponsor](https://camo.githubusercontent.com/7d9333b097b2f54a8957d126ab82937811489c9b75c3850f609985cf94cd29fe/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f2532302d53706f6e736f722532306d652532306f6e2532304769744875622d6f72616e6765)](https://github.com/sponsors/josdejong) - -## Sponsors - - - - - -
- - - - - -

Foresight: Increase CI/CD Health & Test Performance

- -

-Foresight provides full visibility and deep insights into the health -and performance of your tests and CI pipelines. Assess the risk of -changes, resolve bottlenecks, reduce build times, and deliver -high-quality software at speed with Foresight. -

- -[Sign up now!](https://runforesight.com/?utm_source=mathjs&utm_medium=sponsorship) -
+[![Github Sponsor](https://img.shields.io/github/sponsors/josdejong +)](https://github.com/sponsors/josdejong) ## Features -- Supports numbers, big numbers, complex numbers, fractions, units, strings, arrays, and matrices. +- Supports numbers, bignumbers, bigints, complex numbers, fractions, units, strings, arrays, and matrices. - Is compatible with JavaScript's built-in Math library. - Contains a flexible expression parser. - Does symbolic computation. @@ -101,7 +76,7 @@ See the [Getting Started](https://mathjs.org/docs/getting_started.html) for a mo ## Browser support -Math.js works on any ES6 compatible JavaScript engine, including node.js, Chrome, Firefox, Safari, and Edge. +Math.js works on any [ES2020](https://262.ecma-international.org/11.0/) compatible JavaScript engine, including node.js, Chrome, Firefox, Safari, and Edge. ## Documentation @@ -143,13 +118,13 @@ The code of `mathjs` is written in ES modules, and requires all files to have a What mathjs tries to achieve is to offer an environment where you can do calculations with mixed data types, like multiplying a regular `number` with a `Complex` number or a `BigNumber`, and work with all of those in matrices. -Mathjs also allows to add a new data type, like say `BigInt`, with little effort. +Mathjs also allows to add a new data type with little effort. The solution that mathjs uses has two main ingredients: -- **Typed functions**. All functions are created using [`typed-function`](https://github.com/josdejong/typed-function/). This makes it easier to (dynamically) create and extend a single function with new data types, automatically do type conversions on function inputs, etc. So, if you create function multiply for two `number`s, you can extend it with support for multiplying two `BigInts`. If you define a conversion from `BigInt` to `number`, the typed-function will automatically allow you to multiply a `BigInt` with a `number`. +- **Typed functions**. All functions are created using [`typed-function`](https://github.com/josdejong/typed-function/). This makes it easier to (dynamically) create and extend a single function with new data types, automatically do type conversions on function inputs, etc. So, if you create function multiply for two `number`s, you can extend it with support for multiplying your own data type, say `MyDecimal`. If you define a conversion from `MyDecimal` to `number`, the typed-function will automatically allow you to multiply a `MyDecimal` with a `number`. -- **Dependency injection**. When we have a function `multiply` with support for `BigInt`, thanks to the dependency injection, other functions using `multiply` under the hood, like `prod`, will automatically support `BigInt` too. This also works the other way around: if you don't need the heavyweight `multiply` (which supports BigNumbers, matrices, etc), and you just need a plain and simple number support, you can use a lightweight implementation of `multiply` just for numbers, and inject that in `prod` and other functions. +- **Dependency injection**. When we have a function `multiply` with support for `MyDecimal`, thanks to the dependency injection, other functions using `multiply` under the hood, like `prod`, will automatically support `MyDecimal` too. This also works the other way around: if you don't need the heavyweight `multiply` (which supports BigNumbers, matrices, etc), and you just need a plain and simple number support, you can use a lightweight implementation of `multiply` just for numbers, and inject that in `prod` and other functions. At the lowest level, mathjs has immutable factory functions which create immutable functions. The core function `math.create(...)` creates a new instance having functions created from all passed factory functions. A mathjs instance is a collection of created functions. It contains a function like `math.import` to allow extending the instance with new functions, which can then be used in the expression parser. @@ -161,7 +136,7 @@ A common case is to implement a new function. This involves the following steps: - Write documentation on the function in the source code comment of `myNewFunction.js`. This documentation is used to auto generate documentation on the website. - Write embedded documentation for the new function in `./src/expression/embeddedDocs/function/arithmetic/myNewFunction.js`. Add the new documentation to the index file `./src/expression/embeddedDocs/embeddedDocs.js`. - Write unit tests for the function in `./test/unit-tests/function/arithmetic/myNewFunction.test.js`. -- Write a TypeScript definition for the new function in `./types/index.d.ts`, and write tests for it in `./types/index.ts`. Normally, two definitions need to be added: one for the static function `math.myNewFunction(...)` and one for the chained API `math.chain(...).myNewFunction(...)`. +- Write the necessary TypeScript definitions for the new function in `./types/index.d.ts`, and write tests for it in `./test/typescript-tests/testTypes.ts`. This is described in [./types/EXPLANATION.md](./types/EXPLANATION.md). - Ensure the code style is ok by running `npm run lint` (run `npm run format` to fix the code style automatically). @@ -185,6 +160,10 @@ Then, the tests can be executed: npm test +To test the type definitions: + + npm run test:types + Additionally, the tests can be run on FireFox using [headless mode](https://developer.mozilla.org/en-US/Firefox/Headless_mode): npm run test:browser @@ -220,7 +199,10 @@ Thanks Github Actions and BrowserStack for the generous free hosting of this ope ## License -Copyright (C) 2013-2023 Jos de Jong +mathjs is published under the Apache 2.0 license: + +``` +Copyright (C) 2013-2024 Jos de Jong Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -233,3 +215,28 @@ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +``` + +mathjs contains a JavaScript port of the [CSparse](https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source) library, published under the LGPL-2.1+ license: + +``` +CSparse: a Concise Sparse matrix package. +Copyright (c) 2006, Timothy A. Davis. +http://www.suitesparse.com + +-------------------------------------------------------------------------------- + +CSparse is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +CSparse is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this Module; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +``` diff --git a/bin/cli.js b/bin/cli.js index 7852c26549..6d31390894 100755 --- a/bin/cli.js +++ b/bin/cli.js @@ -30,7 +30,7 @@ * cat script.txt | mathjs > results.txt Run input stream, output to file * * @license - * Copyright (C) 2013-2023 Jos de Jong + * Copyright (C) 2013-2024 Jos de Jong * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy @@ -56,10 +56,23 @@ const PRECISION = 14 // decimals * "Lazy" load math.js: only require when we actually start using it. * This ensures the cli application looks like it loads instantly. * When requesting help or version number, math.js isn't even loaded. - * @return {*} + * @return {{ evalute: function, parse: function, math: Object }} */ function getMath () { - return require('../lib/cjs/defaultInstance.js').default + const { create, all } = require('../lib/browser/math.js') + + const math = create(all) + const parse = math.parse + const evaluate = math.evaluate + + // See https://mathjs.org/docs/expressions/security.html#less-vulnerable-expression-parser + math.import({ + 'import': function () { throw new Error('Function import is disabled') }, + 'createUnit': function () { throw new Error('Function createUnit is disabled') }, + 'reviver': function () { throw new Error('Function reviver is disabled') } + }, { override: true }) + + return { math, parse, evaluate } } /** @@ -68,7 +81,7 @@ function getMath () { * @param {*} value */ function format (value) { - const math = getMath() + const { math } = getMath() return math.format(value, { fn: function (value) { @@ -88,7 +101,7 @@ function format (value) { * @return {[Array, String]} completions */ function completer (text) { - const math = getMath() + const { math } = getMath() let matches = [] let keyword const m = /[a-zA-Z_0-9]+$/.exec(text) @@ -113,7 +126,7 @@ function completer (text) { const ignore = ['expr', 'type'] for (const func in math.expression.mathWithTransform) { if (hasOwnProperty(math.expression.mathWithTransform, func)) { - if (func.indexOf(keyword) === 0 && ignore.indexOf(func) === -1) { + if (func.indexOf(keyword) === 0 && !ignore.includes(func)) { matches.push(func) } } @@ -183,7 +196,7 @@ function runStream (input, output, mode, parenthesis) { } // load math.js now, right *after* loading the prompt. - const math = getMath() + const { math, parse } = getMath() // TODO: automatic insertion of 'ans' before operators like +, -, *, / @@ -214,7 +227,7 @@ function runStream (input, output, mode, parenthesis) { case 'evaluate': // evaluate expression try { - let node = math.parse(expr) + let node = parse(expr) let res = node.evaluate(scope) if (math.isResultSet(res)) { @@ -288,7 +301,7 @@ function runStream (input, output, mode, parenthesis) { * @return {string | null} Returns the name when found, else returns null. */ function findSymbolName (node) { - const math = getMath() + const { math } = getMath() let n = node while (n) { @@ -412,9 +425,10 @@ if (version) { // run a stream, can be user input or pipe input runStream(process.stdin, process.stdout, mode, parenthesis) } else { - fs.stat(scripts[0], function (e, f) { - if (e) { - console.log(getMath().evaluate(scripts.join(' ')).toString()) + fs.stat(scripts[0], function (err) { + if (err) { + const { evaluate } = getMath() + console.log(evaluate(scripts.join(' ')).toString()) } else { // work through the queue of scripts scripts.forEach(function (arg) { diff --git a/bin/repl.js b/bin/repl.js index 21c9b1164a..9ad06fef0a 100755 --- a/bin/repl.js +++ b/bin/repl.js @@ -4,7 +4,7 @@ * This simply preloads mathjs and drops you into a REPL to * help interactive debugging. **/ -global.math = require('../lib/cjs/defaultInstance.js').default +global.math = require('../lib/browser/math.js') const repl = require('repl') repl.start({ useGlobal: true }) diff --git a/dist/math.js b/dist/math.js deleted file mode 100644 index b01e410f9f..0000000000 --- a/dist/math.js +++ /dev/null @@ -1,3 +0,0 @@ -// TODO: deprecated since v8, remove this deprecation warning in v9 -throw new Error('The non-minified file "mathjs/dist/math.js" has removed since mathjs@8.0.0. ' + - 'Please use the minified bundle "mathjs/lib/browser/math.js" instead.') diff --git a/dist/math.min.js b/dist/math.min.js deleted file mode 100644 index 2a2391f07b..0000000000 --- a/dist/math.min.js +++ /dev/null @@ -1,3 +0,0 @@ -// TODO: deprecated since v8, remove this deprecation warning in v9 -throw new Error('The file "mathjs/dist/math.min.js" has been moved to "mathjs/lib/browser/math.js" since mathjs@8.0.0. ' + - 'Please load the bundle via the new path.') diff --git a/dist/package.json b/dist/package.json deleted file mode 100644 index 5bbefffbab..0000000000 --- a/dist/package.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "type": "commonjs" -} diff --git a/docs/command_line_interface.md b/docs/command_line_interface.md index 1287e7b82b..6c1722bc33 100644 --- a/docs/command_line_interface.md +++ b/docs/command_line_interface.md @@ -68,10 +68,9 @@ $ mathjs --string --parenthesis=all # Command line debugging (REPL) -For debugging purposes, `bin/repl.js` provides a REPL (Read Evaluate Print Loop) -for interactive testing of mathjs without having to build new build files after every -little change to the source files. You can either start it directly (`./bin/repl.js`) or -via node (`node bin/repl.js`). +The library also provides a REPL (Read Evaluate Print Loop) via `bin/repl.js` which +loads mathjs in a Node.js command line environment. +You can either start it directly (`./bin/repl.js`) or via node (`node bin/repl.js`). You can exit using either [ctrl]-[C] or [ctrl]-[D]. diff --git a/docs/core/configuration.md b/docs/core/configuration.md index 3365794dfe..4084cb9740 100644 --- a/docs/core/configuration.md +++ b/docs/core/configuration.md @@ -8,7 +8,8 @@ import { create, all } from 'mathjs' // create a mathjs instance with configuration const config = { - epsilon: 1e-12, + relTol: 1e-12, + absTol: 1e-15, matrix: 'Matrix', number: 'number', precision: 64, @@ -28,10 +29,14 @@ math.config({ The following configuration options are available: -- `epsilon`. The minimum relative difference used to test equality between two +- `relTol`. The minimum relative difference used to test equality between two compared values. This value is used by all relational functions. Default value is `1e-12`. +- `absTol`. The minimum absolute difference used to test equality between two + compared values. This value is used by all relational functions. + Default value is `1e-15`. + - `matrix`. The default type of matrix output for functions. Available values are: `'Matrix'` (default) or `'Array'`. Where possible, the type of matrix output from functions is determined from @@ -40,21 +45,29 @@ The following configuration options are available: determined by the option `matrix`. In case of mixed matrix inputs, a matrix will be returned always. -- `number`. The type of numeric output for functions which cannot - determine the numeric type from the inputs. For most functions though, - the type of output is determined from the the input: - a number as input will return a number as output, - a BigNumber as input returns a BigNumber as output. - - For example the functions `math.evaluate('2+3')`, `math.parse('2+3')`, - `math.range('1:10')`, and `math.unit('5cm')` use the `number` configuration - setting. But `math.sqrt(4)` will always return the number `2` - regardless of the `number` configuration, because the input is a number. - - Available values are: `'number'` (default), `'BigNumber'`, or `'Fraction'`. - [BigNumbers](../datatypes/bignumbers.js) have higher precision than the default - numbers of JavaScript, and [`Fractions`](../datatypes/fractions.js) store - values in terms of a numerator and denominator. +- `number`. The type used to parse strings into a numeric value or create a new + numeric value internally. + + For most functions, the type of output is determined from the input: + a number as input will return a number as output, a BigNumber as input + returns a BigNumber as output. But for example the functions + `math.evaluate('2+3')`, `math.parse('2+3')`, `math.range('1:10')`, + and `math.unit('5cm')` use the `number` configuration setting. + + Note that `math.sqrt(4)` will always return the number `2` regardless of + the `number` configuration, because the numeric type can be determined from + the input value. + + Available values are: `'number'` (default), `'BigNumber'`, `'bigint'`, or `'Fraction'`. + [BigNumbers](../datatypes/bignumbers.md) have higher precision than the default numbers of JavaScript, + [bigint](../datatypes/bigints.md) can represent large integer numbers, + and [`Fractions`](../datatypes/fractions.md) store values in terms of a numerator and + denominator. + +- `numberFallback`. When `number` is configured for example with value `'bigint'`, + and a value cannot be represented as `bigint` like in `math.evaluate('2.3')`, + the value will be parsed in the type configured with `numberFallback`. + Available values: `'number'` (default) or `'BigNumber'`. - `precision`. The maximum number of significant digits for BigNumbers. This setting only applies to BigNumbers, not to numbers. diff --git a/docs/datatypes/bigints.md b/docs/datatypes/bigints.md new file mode 100644 index 0000000000..4176e2296b --- /dev/null +++ b/docs/datatypes/bigints.md @@ -0,0 +1,54 @@ +# BigInts + +For calculations with large integer numbers, math.js supports the built-in `bigint` data type. + +## Usage + +A bigint can be created either by adding the suffix `n` to a `number`, using the `BigInt` constructor function, or using the util function `math.bigint`: + +```js +42n +BigInt('42') +math.bigint('42') +``` + +Most functions can determine the type of output from the type of input: +a `number` as input will return a `number` as output, a `bigint` as input returns +a `bigint` as output. Functions which cannot determine the type of output +from the input (for example `math.evaluate`) use the default number type `number`, +which can be configured when instantiating math.js. To configure the use of +`bigint` instead of [numbers](numbers.md) by default, configure math.js like: + +```js +math.config({ + number: 'bigint' +}) + +// use math +math.evaluate('70000000000000000123') // bigint 70000000000000000123n +``` + +## Support + +All basic arithmetic functions in math.js support `bigint`. Since `bigint` can only hold integer values, it is not applicable to for example trigonometric functions. When using a `bigint` in a function that does not support it, like `sqrt`, it will convert the `bigint` into a regular `number` and then execute the function: + +```js +math.sin(2n) // number 0.9092974268256817 +``` + +## Conversion + +There are utility functions to convert a `bigint` into a `number` or `BigNumber`: + +```js +// convert a number to bigint or BigNumber +math.bigint(42) // bigint, 42n +math.bignumber(42) // BigNumber, 42 + +// convert a bigint to a number or BigNumber +math.number(42n) // number, 42 +math.bignumber(42n) // BigNumber, 42 + +// losing digits when converting to number +math.number(70000000000000000123n) // number, 7000000000000000000 +``` diff --git a/docs/datatypes/bignumbers.md b/docs/datatypes/bignumbers.md index 220c5d5498..974e937d5b 100644 --- a/docs/datatypes/bignumbers.md +++ b/docs/datatypes/bignumbers.md @@ -24,7 +24,8 @@ math.config({ number: 'BigNumber', // Default type of number: // 'number' (default), 'BigNumber', or 'Fraction' precision: 64, // Number of significant digits for BigNumbers - epsilon: 1e-60 + relTol: 1e-60, + absTol: 1e-63 }) // use math @@ -34,12 +35,12 @@ math.evaluate('0.1 + 0.2') // BigNumber, 0.3 The default precision for BigNumber is 64 digits, and can be configured with the option `precision`. -Note that we also change the configuration of `epsilon` -to be close to the precision limit of our BigNumbers. `epsilon` is used for +Note that we also change the configuration of `relTol` and `absTol` +to be close to the precision limit of our BigNumbers. `relTol` and `absTol` are used for example in relational and rounding functions (`equal`, `larger`, `smaller`, `round`, `floor`, etc) to determine when a value is nearly equal, -see [Equality](numbers.md#equality). If we would leave `epsilon` unchanged, -having the default value of `1e-12`, we could get inaccurate and misleading +see [Equality](numbers.md#equality). If we would leave `relTol` and `absTol` unchanged, +having the default value of `1e-12` and `1e-15` respectively, we could get inaccurate and misleading results since we're now working with a higher precision. diff --git a/docs/datatypes/fractions.md b/docs/datatypes/fractions.md index fa73de4d2a..7edd61b616 100644 --- a/docs/datatypes/fractions.md +++ b/docs/datatypes/fractions.md @@ -1,7 +1,7 @@ # Fractions For calculations with fractions, math.js supports a `Fraction` data type. -Fraction support is powered by [fraction.js](https://github.com/infusion/Fraction.js). +Fraction support is powered by [fraction.js](https://github.com/rawify/Fraction.js). Unlike [numbers](numbers.md) and [BigNumbers](./bignumbers.md), fractions can store numbers with infinitely repeating decimals, for example `1/3 = 0.3333333...`, which can be represented as `0.(3)`, or `2/7` which can be represented as `0.(285714)`. diff --git a/docs/datatypes/index.md b/docs/datatypes/index.md index 5f3cd2e9ce..328422ed11 100644 --- a/docs/datatypes/index.md +++ b/docs/datatypes/index.md @@ -31,6 +31,9 @@ math.sqrt(4.41e2) // 21 // use BigNumbers math.add(math.bignumber(0.1), math.bignumber(0.2)) // BigNumber, 0.3 +// use bigint +math.add(300000000000000000n, 1n) // 300000000000000001n + // use Fractions math.add(math.fraction(1), math.fraction(3)) // Fraction, 0.(3) diff --git a/docs/datatypes/matrices.md b/docs/datatypes/matrices.md index f15ceeeb79..4f888d6b4b 100644 --- a/docs/datatypes/matrices.md +++ b/docs/datatypes/matrices.md @@ -30,8 +30,8 @@ const array = [[2, 0], [-1, 3]] // Array const matrix = math.matrix([[7, 1], [-2, 3]]) // Matrix // perform a calculation on an array and matrix -math.square(array) // Array, [[4, 0], [1, 9]] -math.square(matrix) // Matrix, [[49, 1], [4, 9]] +math.map(array, math.square) // Array, [[4, 0], [1, 9]] +math.map(matrix, math.square) // Matrix, [[49, 1], [4, 9]] // perform calculations with mixed array and matrix input math.add(array, matrix) // Matrix, [[9, 1], [-3, 6]] @@ -122,14 +122,14 @@ math.range(3, -1, -1) // [3, 2, 1, 0] ## Calculations -All relevant functions of math.js support matrices and arrays. +Most functions of math.js support matrices and arrays. Unary functions can be applied element-wise using via `math.map(matrix, function)`. ```js -// perform a calculation on a matrix +// perform an element-wise operation on a matrix using math.map const a = math.matrix([1, 4, 9, 16, 25]) // Matrix, [1, 4, 9, 16, 25] -math.sqrt(a) // Matrix, [1, 2, 3, 4, 5] +math.map(a, math.sqrt) // Matrix, [1, 2, 3, 4, 5] -// perform a calculation on an array +// use a function that has built-in matrix and array support const b = [1, 2, 3, 4, 5] math.factorial(b) // Array, [1, 2, 6, 24, 120] @@ -138,14 +138,35 @@ const c = [[2, 0], [-1, 3]] // Array const d = math.matrix([[7, 1], [-2, 3]]) // Matrix math.multiply(c, d) // Matrix, [[14, 2], [-13, 8]] -// add a number to a matrix +// add a number to a matrix (see broadcasting) math.add(c, 2) // Array, [[4, 2], [1, 5]] // calculate the determinant of a matrix math.det(c) // 6 math.det(d) // 23 ``` +## Broadcasting +Functions that require two or more matrix like arguments that operate elementwise automatically operate as if the arguments were the same size. + +```js +A = math.matrix([1, 2]) // Matrix, [1, 2] +math.add(A, 3) // Matrix, [3, 4] + +B = math.matrix([[3], [4]]) // Matrix, [[3], [4]] +math.add(A, B) // Matrix, [[4, 5], [5, 6]] +``` +Any index that is in one of the arguments, can be found as if it existed on the others when the size on that dimension is one or not existing. This is valid in N dimensions. + +It's not possible to broadcast in cases where the size in that dimension is higher than one. + +```js +math.add([1, 2], [3, 4, 5]) +// Error: shape missmatch: missmatch is found in arg with shape (2) not possible to broadcast dimension 0 with size 2 to size 3 + +math.add([[1], [2], [3]], [[4], [5]]) +// Error: shape missmatch: missmatch is found in arg with shape (2,1) not possible to broadcast dimension 0 with size 2 to size 3 +``` ## Size and Dimensions @@ -222,8 +243,8 @@ b.resize([2]) // Matrix, size [2], [7, 7] Outer dimensions of a matrix can be squeezed using the function `squeeze`. When -getting or setting a subset in a matrix, the subset is automatically squeezed -or unsqueezed. +getting or setting a single value in a matrix using `subset`, the value is automatically squeezed +or unsqueezed too. ```js // squeeze a matrix @@ -231,9 +252,10 @@ const a = [[[0, 1, 2]]] math.squeeze(a) // [0, 1, 2] math.squeeze([[3]]) // 3 -// subsets are automatically squeezed +// when getting/setting a single value in a matrix using subset, +// it automatically squeeze/unsqueeze the value const b = math.matrix([[0, 1], [2, 3]]) -b.subset(math.index(1, 0)) // 2 +b.subset(math.index(1, 0)) // 2 and not [[2]] ``` @@ -248,12 +270,17 @@ in the matrix, and if not, a subset of the matrix will be returned. A subset can be defined using an `Index`. An `Index` contains a single value or a set of values for each dimension of a matrix. An `Index` can be -created using the function `index`. -Matrix indexes in math.js are zero-based, like most programming languages -including JavaScript itself. +created using the function `index`. When getting a single value from a matrix, +`subset` will return the value itself instead of a matrix containing just this +value. + +The function `subset` normally returns a subset, but when getting or setting a +single value in a matrix, the value itself is returned. -Note that mathematical applications like Matlab and Octave work differently, -as they use one-based indexes. + +Matrix indexes in math.js are zero-based, like most programming languages +including JavaScript itself. Note that mathematical applications like Matlab +and Octave work differently, as they use one-based indexes. ```js // create some matrices @@ -304,6 +331,49 @@ method `.set()`, the matrix will be resized. By default, new items will be initialized with zero, but it is possible to specify an alternative value using the optional third argument `defaultValue`. +## Advanced Indexing + +Boolean array indexing is a technique that allows you to filter, replace, and set values in an array based on logical conditions. This can be done by creating a boolean array that represents the desired conditions, and then using that array as an index to select the elements of the original array that meet those conditions. + +For example, a boolean array can be created to represent all the even numbers in an array, and then used to filter the original array to only include the even numbers. Alternatively, a boolean array can be created to represent all the elements of an array that are greater than a certain value, and then used to replace all the elements of the original array that are greater than that value with a new value. + + +```js +const q = [1, 2, 3, 4] +math.subset(q, math.index([true, false, true, false])) // Array [1, 3] + +// filtering +math.subset(q, math.index(math.larger(q, 2))) // Array [3, 4] + +// filtering with no matches +math.subset(q, math.index(math.larger(q, 5))) // Array [] + +// setting specific values, please note that the replacement value is broadcasted +q = math.subset(q, math.index(math.smaller(q, 3)), 0) // q = [0, 0, 3, 4] + +// replacing specific values +math.subset(q, math.index(math.equal(q, 0)), [1, 2]) // q = [1, 2, 3, 4] +``` + +The same can be accomplished in the parser in a much more compact manner. Please note that everything after `#` are comments. +```js +math.evaluate(` +q = [1, 2, 3, 4] +q[[true, false, true, false]] # Matrix [1, 3] +q[q>2] # Matrix [3, 4] +q[q>5] # Matrix [] +q[q <3] = 0 # q = [0, 0, 3, 4] +q[q==0] = [1, 2] # q = [1, 2, 3, 4] +`) +``` +The expression inside the index can be as complex as needed as long it evaluates to an array of booleans of the same size. +```js +math.evaluate(` +q = [1, 2, 3, 4] +r = [6, 5, 4, 3] +q[q > 3 and r < 4] # [4] +`) +``` ## Iterating @@ -344,6 +414,39 @@ const cum = a.map(function (value, index, matrix) { console.log(cum.toString()) // [[0, 1], [3, 6], [10, 15]] ``` +### Iterating over multiple Matrixes or Arrays + +You can iterate over multiple matrices or arrays by using the `map` function. Mapping allows to perform element-wise operations on matrices by automatically adjusting their sizes to match each other. + +To iterate over multiple matrices, you can use the `map` function. The `map` function applies a given function to each element of the matrices and returns a new matrix with the results. + +Here's an example of iterating over two matrices and adding their corresponding elements: + +```js +const a = math.matrix([[1, 2], [3, 4]]); +const b = math.matrix([[5, 6], [7, 8]]); + +const result = math.map(a, b, (x, y) => x + y); + +console.log(result); // [[6, 8], [10, 12]] +``` + +In this example, the `map` function takes matrices as the first two arguments and a callback function `(x, y) => x + y` as the third argument. The callback function is applied to each element of the matrices, where `x` represents the corresponding element from matrix `a` and `y` represents the corresponding element from matrix `b`. The result is a new matrix with the element-wise sum of the two matrices. + +By using broadcasting and the `map` function, you can easily iterate over multiple matrices and perform element-wise operations. + +```js +const a = math.matrix([10, 20]) +const b = math.matrix([[3, 4], [5, 6]]) + +const result = math.map(a, b, (x, y) => x + y) +console.log(result); // [[13, 24], [15, 26]] +``` + +It's also possible to provide a callback with an index and the broadcasted arrays. Like `(valueA, valueB, index)` or even `(valueA, valueB, index, broadcastedMatrixA, broadcastedMatrixB)`. There is no specific limit for the number of matrices `N` that can be mapped. Thus, the callback can have `N` arguments, `N+1` arguments in the case of including the index, or `2N+1` arguments in the case of including the index and the broadcasted matrices in the callback. + +At this moment `forEach` doesn't include the same functionality. + ## Storage types Math.js supports both dense matrices as well as sparse matrices. Sparse matrices are efficient for matrices largely containing zeros. In that case they save a lot of memory, and calculations can be much faster than for dense matrices. diff --git a/docs/datatypes/numbers.md b/docs/datatypes/numbers.md index 29e7534b21..f082d5cd6f 100644 --- a/docs/datatypes/numbers.md +++ b/docs/datatypes/numbers.md @@ -50,7 +50,7 @@ const ans = math.add(0.1, 0.2) // 0.30000000000000004 math.format(ans, {precision: 14}) // '0.3' ``` -Alternatives are to use [Fractions](fractions.md) which store a number as a numerator and denominator, or [BigNumbers](bignumbers.md), which store a number with a higher precision. +Alternatives are to use [Fractions](fractions.md) which store a number as a numerator and denominator, [BigNumbers](bignumbers.md) which store a number with a higher precision, or [bigint](bigints.md) which can store larger integer numbers. ## Minimum and maximum @@ -73,16 +73,14 @@ false, as the addition `0.1 + 0.2` introduces a round-off error and does not return exactly `0.3`. To solve this problem, the relational functions of math.js check whether the -relative difference between the compared values is smaller than the configured -option `epsilon`. In pseudo code (without exceptions for 0, Infinity and NaN): +relative and absolute differences between the compared values is smaller than the configured +option `relTol` and `absTol`. In pseudo code (without exceptions for 0, Infinity and NaN): - diff = abs(x - y) - nearlyEqual = (diff <= max(abs(x), abs(y)) * EPSILON) OR (diff < DBL_EPSILON) + abs(a-b) <= max(relTol * max(abs(a), abs(b)), absTol) where: - - `EPSILON` is the relative difference between x and y. Epsilon is configurable - and is `1e-12` by default. See [Configuration](../core/configuration.md). + - `relTol` is the relative tolerance between x and y and `absTol` the absolute tolerance. Relative tolerance and absolute tolerance are configurable and are `1e-12` and `1e-15` respectively by default. See [Configuration](../core/configuration.md). - `DBL_EPSILON` is the minimum positive floating point number such that `1.0 + DBL_EPSILON !== 1.0`. This is a constant with a value of approximately `2.2204460492503130808472633361816e-16`. diff --git a/docs/datatypes/units.md b/docs/datatypes/units.md index fbf0d5f516..6ae2adde8e 100644 --- a/docs/datatypes/units.md +++ b/docs/datatypes/units.md @@ -29,16 +29,16 @@ const c = math.unit('2 inch') // Unit 2 inch const d = math.unit('90 km/h') // Unit 90 km/h const e = math.unit('101325 kg/(m s^2)') // Unit 101325 kg / (m s^2) -const d = c.to('cm') // Unit 5.08 cm +const f = c.to('cm') // Unit 5.08 cm b.toNumber('gram') // Number 100 math.number(b, 'gram') // Number 100 c.equals(a) // false -c.equals(d) // true +c.equals(f) // true c.equalBase(a) // true c.equalBase(b) // false -d.toString() // String "5.08 cm" +f.toString() // String "5.08 cm" const kph = math.unit('km/h') // valueless Unit km/h const mps = math.unit('m/s') // valueless Unit m/s @@ -50,17 +50,27 @@ Use care when creating a unit with multiple terms in the denominator. Implicit m ```js // These three are identical -const correct1 = math.unit('8.314 m^3 Pa / mol / K') // Unit 8.314 (m^3 Pa) / (mol K) -const correct2 = math.unit('8.314 (m^3 Pa) / (mol K)') // Unit 8.314 (m^3 Pa) / (mol K) -const correct3 = math.unit('8.314 (m^3 * Pa) / (mol * K)') // Unit 8.314 (m^3 Pa) / (mol K) +const correct1 = math.unit('8.314 m^3 Pa / mol / K') // Unit 8.314 (m^3 Pa) / (mol K) +const correct2 = math.unit('8.314 (m^3 Pa) / (mol K)') // Unit 8.314 (m^3 Pa) / (mol K) +const correct3 = math.unit('8.314 (m^3 * Pa) / (mol * K)') // Unit 8.314 (m^3 Pa) / (mol K) ``` But this expression, which omits the second `/` between `mol` and `K`, results in the wrong value: ```js // Missing the second '/' between 'mol' and 'K' -const incorrect = math.unit('8.314 m^3 Pa / mol K') // Unit 8.314 (m^3 Pa K) / mol +const incorrect = math.unit('8.314 m^3 Pa / mol K') // Unit 8.314 (m^3 Pa K) / mol ``` +The function `math.unit` has its own small parser. This parser differs a bit from the expression parser `math.evaluate`, and returns the expected result in this case: + +```js +// using math.evaluate instead of math.unit +const correct4 = math.evaluate('8.314 (m^3 * Pa) / (mol * K)') // Unit 8.314 (m^3 Pa) / (mol K) +``` + +In summary: be careful with implicit multiplication. In case of doubt, always use an explicit `*` and parenthesis. + + ## Calculations The operations that support units are `add`, `subtract`, `multiply`, `divide`, `pow`, `abs`, `sqrt`, `square`, `cube`, and `sign`. @@ -69,7 +79,7 @@ Trigonometric functions like `cos` are also supported when the argument is an an ```js const a = math.unit(45, 'cm') // Unit 450 mm const b = math.unit('0.1m') // Unit 100 mm -math.add(a, b) // Unit 0.65 m +math.add(a, b) // Unit 0.55 m math.multiply(b, 2) // Unit 200 mm const c = math.unit(45, 'deg') // Unit 45 deg @@ -95,18 +105,15 @@ const F = math.multiply(q, math.cross(v, B)) // [0 N, 0 N, -1 N] All arithmetic operators act on the value of the unit as it is represented in SI units. This may lead to surprising behavior when working with temperature scales like `celsius` (or `degC`) and `fahrenheit` (or `degF`). -In general you should avoid calculations using `celsius` and `fahrenheit`. Rather, use `kelvin` (or `K`) and `rankine` (or `degR`) instead. +In general, you should avoid calculations using `celsius` and `fahrenheit`. Rather, use `kelvin` (or `K`) and `rankine` (or `degR`) instead. This example highlights some problems when using `celsius` and `fahrenheit` in calculations: ```js const T_14F = math.unit('14 degF') // Unit 14 degF (263.15 K) -const T_28F = math.multiply(T1, 2) // Unit 487.67 degF (526.3 K), not 28 degF +const T_28F = math.multiply(T_14F, 2) // Unit 28 degF (270.93 K), not 526.3 K const Tnegative = math.unit(-13, 'degF') // Unit -13 degF (248.15 K) -const Tpositive = math.abs(T1) // Unit -13 degF (248.15 K), not 13 degF - -const Trate1 = math.evaluate('5 (degC/hour)') // Unit 5 degC/hour -const Trate2 = math.evaluate('(5 degC)/hour') // Unit 278.15 degC/hour +const Tpositive = math.abs(Tnegative) // Unit -13 degF (248.15 K), not 13 degF ``` The expression parser supports units too. This is described in the section about @@ -117,7 +124,7 @@ units on the page [Syntax](../expressions/syntax.md#units). You can add your own units to Math.js using the `math.createUnit` function. The following example defines a new unit `furlong`, then uses the user-defined unit in a calculation: ```js -math.createUnit('furlong', '220 yards') +math.createUnit('furlong', '220 yards') math.evaluate('1 mile to furlong') // 8 furlong ``` @@ -125,7 +132,7 @@ If you cannot express the new unit in terms of any existing unit, then the secon ```js // A 'foo' cannot be expressed in terms of any other unit. -math.createUnit('foo') +math.createUnit('foo') math.evaluate('8 foo * 4 feet') // 32 foo feet ``` @@ -196,6 +203,26 @@ math.createUnit('θ', '1 rad') math.evaluate('1θ + 3 deg').toNumber('deg') // 60.29577951308232 ``` +## Numeric type of the value of a unit + +The built-in units are always created with a value being a `number`. To turn the value into for example a `BigNumber` or `Fraction`, you can convert the value using the function `math.fraction` and `math.bignumber`: + +```js +math.unit(math.fraction(10), 'inch').toNumeric('cm') // Fraction 127/5 +math.fraction(math.unit(10, 'inch')).toNumeric('cm') // Fraction 127/5 + +math.bignumber(math.unit(10, 'inch')).toNumeric('cm') // BigNumber 25.4 +math.unit(math.bignumber(10), 'inch').toNumeric('cm') // BigNumber 25.4 +``` + +When using the expression parser, it is possible to configure numeric values to be parsed as `Fraction` or `BigNumber`: + +```js +math.config({ number: 'Fraction' }) +math.evaluate('10 inch').toNumeric('cm') // Fraction 127/5 +``` + + ## API A `Unit` object contains the following functions: @@ -311,6 +338,8 @@ peta | P | 1e15 exa | E | 1e18 zetta | Z | 1e21 yotta | Y | 1e24 +ronna | R | 1e27 +quetta | Q | 1e30 Name | Abbreviation | Value ------ | ------------- | ----- @@ -324,6 +353,8 @@ femto | f | 1e-15 atto | a | 1e-18 zepto | z | 1e-21 yocto | y | 1e-24 +ronto | r | 1e-27 +quecto | q | 1e-30 The following binary prefixes are available. They can be used with units `bits` (`b`) and `bytes` (`B`). diff --git a/docs/expressions/customization.md b/docs/expressions/customization.md index 20895b2f8e..6fff36c65c 100644 --- a/docs/expressions/customization.md +++ b/docs/expressions/customization.md @@ -107,16 +107,20 @@ allowing the function to process the arguments in a customized way. Raw functions are called as: ``` -rawFunction(args: Node[], math: Object, scope: Object) +rawFunction(args: Node[], math: Object, scope: Map) ``` Where : - `args` is an Array with nodes of the parsed arguments. - `math` is the math namespace against which the expression was compiled. -- `scope` is a shallow _copy_ of the `scope` object provided when evaluating - the expression, optionally extended with nested variables like a function - parameter `x` of in a custom defined function like `f(x) = x^2`. +- `scope` is a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) + interface containing the variables defined in the scope + passed via `evaluate(scope)`. The passed scope is always a `Map` interface, + and normally a `PartitionedMap` is used to separate local function variables + like `x` in a custom defined function `f(x) = rawFunction(x) ^ 2` from the + scope variables. Note that a `PartitionedMap` can recursively link to another + `PartitionedMap`. Raw functions must be imported in the `math` namespace, as they need to be processed at compile time. They are not supported when passed via a scope diff --git a/docs/expressions/expression_trees.md b/docs/expressions/expression_trees.md index 9dfc24a125..945f4fb9af 100644 --- a/docs/expressions/expression_trees.md +++ b/docs/expressions/expression_trees.md @@ -20,7 +20,7 @@ In this case, the expression `sqrt(2 + x)` is parsed as: ConstantNode 2 x SymbolNode ``` -Alternatively, this expression tree can be build by manually creating nodes: +Alternatively, this expression tree can be built by manually creating nodes: ```js const node1 = new math.ConstantNode(2) @@ -213,7 +213,7 @@ All nodes have the following methods: this node and each of its child nodes. Similar to `Array.forEach`, except recursive. The callback function is a mapping function accepting a node, and returning - a replacement for the node or the original node. Function `callback` is + nothing. Function `callback` is called as `callback(node: Node, path: string, parent: Node)` for every node in the tree. Parameter `path` is a string containing a relative JSON Path. Example: @@ -291,7 +291,8 @@ Examples: const node1 = math.parse('a[3]') const object = new math.SymbolNode('a') -const index = new math.IndexNode([3]) +const constant3 = new math.ConstantNode(3) +const index = new math.IndexNode([constant3]) const node2 = new math.AccessorNode(object, index) ``` @@ -527,7 +528,7 @@ const three = new math.ConstantNode(3) const range = new math.RangeNode(one, three) const index = new math.IndexNode([range, two]) -const node2 = new math.AccessNode(A, index) +const node2 = new math.AccessorNode(A, index) ``` ### ObjectNode diff --git a/docs/expressions/parsing.md b/docs/expressions/parsing.md index df7c1149e5..5dd2ebce19 100644 --- a/docs/expressions/parsing.md +++ b/docs/expressions/parsing.md @@ -22,9 +22,19 @@ math.evaluate([expr1, expr2, expr3, ...], scope) Function `evaluate` accepts a single expression or an array with expressions as the first argument and has an optional second argument -containing a scope with variables and functions. The scope can be a regular -JavaScript Object, or Map. The scope will be used to resolve symbols, and to write -assigned variables or function. +containing a `scope` with variables and functions. The scope can be a regular +JavaScript `Map` (recommended), a plain JavaScript `object`, or any custom +class that implements the `Map` interface with methods `get`, `set`, `keys` +and `has`. The scope will be used to resolve symbols, and to write assigned +variables and functions. + +When an `Object` is used as scope, mathjs will internally wrap it in an +`ObjectWrappingMap` interface since the internal functions can only use a `Map` +interface. In case of custom defined functions like `f(x) = x^2`, the scope +will be wrapped in a `PartitionedMap`, which reads and writes the function +variables (like `x` in this example) from a temporary map, and reads and writes +other variables from the original scope. The original scope is never copied, it +is only wrapped around when needed. The following code demonstrates how to evaluate expressions. @@ -167,7 +177,9 @@ The parser contains the following functions: - `get(name)` Retrieve a variable or function from the parser's scope. - `getAll()` - Retrieve a map with all defined a variables from the parser's scope. + Retrieve an object with all defined variables in the parser's scope. +- `getAllAsMap()` + Retrieve a map with all defined variables in the parser's scope. - `remove(name)` Remove a variable or function from the parser's scope. - `set(name, value)` @@ -192,7 +204,7 @@ parser.evaluate('f(x, y) = x^y') // f(x, y) parser.evaluate('f(2, 3)') // 8 // get and set variables and functions -const x = parser.get('x') // x = 7 +const x = parser.get('x') // x = 3.5 const f = parser.get('f') // function const g = f(3, 3) // g = 27 parser.set('h', 500) diff --git a/docs/expressions/security.md b/docs/expressions/security.md index 03c90929dc..62ac1df8cf 100644 --- a/docs/expressions/security.md +++ b/docs/expressions/security.md @@ -39,9 +39,10 @@ There is a small number of functions which yield the biggest security risk in the expression parser: - `import` and `createUnit` which alter the built-in functionality and - allow overriding existing functions and units. -- `evaluate`, `parse`, `simplify`, and `derivative` which parse arbitrary - input into a manipulable expression tree. + allow overriding existing functions and units, and `reviver` which parses + values into class instances. +- `evaluate`, `parse`, `simplify`, `derivative`, and `resolve` which parse + arbitrary input into a manipulable expression tree. To make the expression parser less vulnerable whilst still supporting most functionality, these functions can be disabled: @@ -53,12 +54,17 @@ const math = create(all) const limitedEvaluate = math.evaluate math.import({ + // most important (hardly any functional impact) 'import': function () { throw new Error('Function import is disabled') }, 'createUnit': function () { throw new Error('Function createUnit is disabled') }, + 'reviver': function () { throw new Error('Function reviver is disabled') }, + + // extra (has functional impact) 'evaluate': function () { throw new Error('Function evaluate is disabled') }, 'parse': function () { throw new Error('Function parse is disabled') }, 'simplify': function () { throw new Error('Function simplify is disabled') }, - 'derivative': function () { throw new Error('Function derivative is disabled') } + 'derivative': function () { throw new Error('Function derivative is disabled') }, + 'resolve': function () { throw new Error('Function resolve is disabled') }, }, { override: true }) console.log(limitedEvaluate('sqrt(16)')) // Ok, 4 @@ -71,7 +77,7 @@ console.log(limitedEvaluate('parse("2+3")')) // Error: Function parse is disable You found a security vulnerability? Awesome! We hope you don't have bad intentions and want to help fix the issue. Please report the vulnerability in a private way by contacting one of the maintainers -via mail or an other private channel. That way we can work together +via mail or another private channel. That way we can work together on a fix before sharing the issue with everybody including the bad guys. ## Stability risks diff --git a/docs/expressions/syntax.md b/docs/expressions/syntax.md index 6b4db1be20..07a081a228 100644 --- a/docs/expressions/syntax.md +++ b/docs/expressions/syntax.md @@ -114,25 +114,33 @@ Operators | Description `!` | Factorial `^`, `.^` | Exponentiation `+`, `-`, `~`, `not` | Unary plus, unary minus, bitwise not, logical not +`%`, `mod` | percentage, modulus See section below | Implicit multiplication -`*`, `/`, `.*`, `./`, `%`, `mod` | Multiply, divide, percentage, modulus +`*`, `/`, `.*`, `./` | Multiply, divide `+`, `-` | Add, subtract `:` | Range `to`, `in` | Unit conversion `<<`, `>>`, `>>>` | Bitwise left shift, bitwise right arithmetic shift, bitwise right logical shift `==`, `!=`, `<`, `>`, `<=`, `>=` | Relational -`&` | Bitwise and +`&` | Bitwise and (lazily evaluated) ^| | Bitwise xor -| | Bitwise or -`and` | Logical and +| | Bitwise or (lazily evaluated) +`and` | Logical and (lazily evaluated) `xor` | Logical xor -`or` | Logical or +`or` | Logical or (lazily evaluated) `?`, `:` | Conditional expression `=` | Assignment `,` | Parameter and column separator `;` | Row separator `\n`, `;` | Statement separators +Lazy evaluation is used where logically possible for bitwise and logical +operators. In the following example, the value of `x` will not even be +evaluated because it cannot effect the final result: +```js +math.evaluate('false and x') // false, no matter what x equals +``` + ## Functions @@ -242,6 +250,68 @@ Note that math.js embodies a preference for the operator forms, in that calling `simplify` (see [Algebra](./algebra.md)) converts any instances of the function form into the corresponding operator. +## Map and forEach + +The `map` and `forEach` functions can be used to apply a callback function to each element of an array or matrix. + +The callback functions can be functions, typed functions, inline functions (only in the parser) or compiled inline functions (only in the parser). + +The callback can have the following inputs: +- **value**: the current value in the array or matrix. +- **index**: the index of the current value expressed as an array of numbers. +- **array**: the array or matrix being iterated. + +Below is the syntax for both functions: + +### map + +The `map` function applies a function to each element of an array and returns a new array with the results. + +```js +const parser = math.parser() + +// Define a square function +parser.evaluate('square(x) = x ^ 2') + +// Apply the square function to each element of the array +parser.evaluate('result = map([1, 2, 3, 4], square)') +// result: [1, 4, 9, 16] + +// Apply an inline function to each element of the array +parser.evaluate('result = map([1, 2, 3, 4], f(x) = x ^ 2)') +// result: [1, 4, 9, 16] + +// Apply a compiled inline function to each element of the array +parser.evaluate('result = map([1, 2, 3, 4], x ^ 2)') +// result: [1, 4, 9, 16] +``` + +### forEach +The `forEach` function applies a function to each element of an array or matrix but does not return a new array. It is useful for executing side effects. + +```js +// Define a function that prints each element +math.import({consoleLog: x => console.log(x)}) +const parser = math.parser() + +// Define a squareConsleLog function +parser.evaluate('squareConsoleLog(x) = consoleLog(x ^ 2)') + +// Apply the squareConsleLog function to each element of the array +parser.evaluate('forEach([1, 2, 3, 4], squareConsleLog)') +// Prints: 1, 4, 9, 16 + +// Apply an inline function to each element of the array +parser.evaluate('forEach([1, 2, 3, 4], f(x) = consoleLog(x ^ 2))') +// Prints: 1, 4, 9, 16 + +// Apply a compiled inline function to each element of the array +parser.evaluate('forEach([1, 2, 3, 4], consoleLog(x ^ 2))') +// Prints: 1, 4, 9, 16 +``` + +These functions are useful for performing element-wise operations on arrays or matrices. + ## Constants and variables Math.js has a number of built-in constants such as `pi` and `e`. @@ -465,19 +535,6 @@ parser.evaluate('i * i') // Number, -1 parser.evaluate('sqrt(-4)') // Complex, 2i ``` -Math.js does not automatically convert complex numbers with an imaginary part -of zero to numbers. They can be converted to a number using the function -`number`. - -```js -// convert a complex number to a number -const parser = math.parser() -parser.evaluate('a = 2 + 3i') // Complex, 2 + 3i -parser.evaluate('b = a - 3i') // Complex, 2 + 0i -parser.evaluate('number(b)') // Number, 2 -parser.evaluate('number(a)') // Error: 2 + i is no valid number -``` - ### Units diff --git a/docs/index.md b/docs/index.md index f3e77f96e3..47e0340a56 100644 --- a/docs/index.md +++ b/docs/index.md @@ -26,6 +26,7 @@ Math.js can be used in the browser, in node.js and in any JavaScript engine. Ins - **[Data Types](datatypes/index.md)** - [Numbers](datatypes/numbers.md) - [BigNumbers](datatypes/bignumbers.md) + - [bigints](datatypes/bigints.md) - [Fractions](datatypes/fractions.md) - [Complex Numbers](datatypes/complex_numbers.md) - [Matrices](datatypes/matrices.md) diff --git a/docs/reference/classes.md b/docs/reference/classes.md index 89545728ac..fdc9844d1a 100644 --- a/docs/reference/classes.md +++ b/docs/reference/classes.md @@ -24,7 +24,7 @@ Stores values for a scalar unit and its postfix. (eg `100 mm` or `100 kg`). Alth Stores values for a fractional number. - [Overview](../datatypes/fractions.md) -- [Class API](https://github.com/infusion/Fraction.js/) +- [Class API](https://github.com/rawify/Fraction.js) ## BigNumber @@ -46,7 +46,7 @@ Classes used internally that may be of use to developers: - [Index](classes/matrixindex.md) - [Range](classes/matrixrange.md) -- [ResultSet](classes/matrixrange.md) +- [ResultSet](classes/resultset.md) - [FibonacciHeap](classes/fibonacciheap.md) ## Complex diff --git a/examples/advanced/convert_fraction_to_bignumber.js b/examples/advanced/convert_fraction_to_bignumber.js index d3903cde1d..c06b245a48 100644 --- a/examples/advanced/convert_fraction_to_bignumber.js +++ b/examples/advanced/convert_fraction_to_bignumber.js @@ -13,7 +13,7 @@ // Create an empty math.js instance, with only typed // (every instance contains `import` and `config` also out of the box) -const { create, typedDependencies, all } = require('../..') +import { create, typedDependencies, all } from '../../lib/esm/index.js' const math = create({ typedDependencies }) @@ -27,16 +27,14 @@ const allExceptLoaded = Object.keys(all) math.config({ number: 'Fraction' }) // Add a conversion from Faction -> BigNumber -// this conversion: -// - must be inserted in the conversions list before the conversion Fraction -> number -// - must be added to the conversions before loading functions into math.js -math.typed.conversions.unshift({ +// This conversion will to override the existing conversion from Fraction to +// BigNumber. It must be added *after* the default conversions are loaded +// and *before* the actual functions are imported into math.js. +math.typed.addConversion({ from: 'Fraction', to: 'BigNumber', - convert: function (fraction) { - return new math.BigNumber(fraction.n).div(fraction.d) - } -}) + convert: (fraction) => new math.BigNumber(fraction.n).div(fraction.d) +}, { override: true }) // Import all data types, functions, constants, the expression parser, etc. math.import(allExceptLoaded) diff --git a/examples/advanced/custom_argument_parsing.js b/examples/advanced/custom_argument_parsing.js index 19198b8df3..c5ef1b97d3 100644 --- a/examples/advanced/custom_argument_parsing.js +++ b/examples/advanced/custom_argument_parsing.js @@ -7,7 +7,7 @@ * will be invoked with unevaluated arguments, allowing the function * to process the arguments in a customized way. */ -const { create, all } = require('../..') +import { create, all } from '../../lib/esm/index.js' const math = create(all) /** @@ -43,7 +43,7 @@ function integrate (f, start, end, step) { * @param {Array.} args * Expects the following arguments: [f, x, start, end, step] * @param {Object} math - * @param {Object} [scope] + * @param {Map} [scope] */ integrate.transform = function (args, math, scope) { // determine the variable name @@ -57,16 +57,12 @@ integrate.transform = function (args, math, scope) { const end = args[3].compile().evaluate(scope) const step = args[4] && args[4].compile().evaluate(scope) // step is optional - // create a new scope, linked to the provided scope. We use this new scope - // to apply the variable. - const fnScope = Object.create(scope) - // construct a function which evaluates the first parameter f after applying // a value for parameter x. const fnCode = args[0].compile() const f = function (x) { - fnScope[variable] = x - return fnCode.evaluate(fnScope) + scope.set(variable, x) + return fnCode.evaluate(scope) } // execute the integration @@ -80,7 +76,7 @@ integrate.transform.rawArgs = true // import the function into math.js. Raw functions must be imported in the // math namespace, they can't be used via `evaluate(scope)`. math.import({ - integrate: integrate + integrate }) // use the function in JavaScript @@ -93,6 +89,6 @@ console.log(math.integrate(f, 0, 1)) // outputs 0.6667254718034714 console.log(math.evaluate('integrate(x^0.5, x, 0, 1)')) // outputs 0.6667254718034714 // use the function via the expression parser (2) -const scope = {} +const scope = new Map() math.evaluate('f(x) = 2 * x', scope) console.log(math.evaluate('integrate(f(x), x, 0, 2)', scope)) // outputs 4.000000000000003 diff --git a/examples/advanced/custom_datatype.js b/examples/advanced/custom_datatype.js index ea83d3beaf..52bd2bc6c6 100644 --- a/examples/advanced/custom_datatype.js +++ b/examples/advanced/custom_datatype.js @@ -1,7 +1,8 @@ // This example demonstrates importing a custom data type, // and extending an existing function (add) with support for this data type. -const { create, factory, all } = require('../..') +import { all, create, factory } from '../../lib/esm/index.js' + const math = create(all) // factory function which defines a new data type CustomValue diff --git a/examples/advanced/custom_evaluate_using_factories.js b/examples/advanced/custom_evaluate_using_factories.js index e8788453b3..a96ea40e37 100644 --- a/examples/advanced/custom_evaluate_using_factories.js +++ b/examples/advanced/custom_evaluate_using_factories.js @@ -1,4 +1,7 @@ -const { create, evaluateDependencies, factory } = require('../..') +// we use the number only implementation in order to not pull in +// the `Unit` class for example. when using as library, +// use import 'mathjs/number' +import { create, evaluateDependencies, factory } from '../../lib/esm/number.js' // custom implementations of all functions you want to support const add = (a, b) => a + b diff --git a/examples/advanced/custom_evaluate_using_import.js b/examples/advanced/custom_evaluate_using_import.js index 3c486b3be3..6e7d976ce4 100644 --- a/examples/advanced/custom_evaluate_using_import.js +++ b/examples/advanced/custom_evaluate_using_import.js @@ -1,4 +1,7 @@ -const { create, evaluateDependencies } = require('../..') +// we use the number only implementation in order to not pull in +// the `Unit` class for example. when using as library, +// use require('mathjs/number') +import { create, evaluateDependencies } from '../../lib/esm/number.js' // custom implementations of all functions you want to support const add = (a, b) => a + b @@ -8,7 +11,7 @@ const divide = (a, b) => a / b // create a mathjs instance with hardly any functions // there are some functions created which are used internally by evaluate though, -// for example by the Unit class which has dependencies on addScalar, subtract, +// for example by the Unit class which has dependencies on addScalar, subtractScalar, // multiplyScalar, etc. const math = create(evaluateDependencies) diff --git a/examples/advanced/custom_loading.mjs b/examples/advanced/custom_loading.js similarity index 95% rename from examples/advanced/custom_loading.mjs rename to examples/advanced/custom_loading.js index 9024dc215a..f522d0a83c 100644 --- a/examples/advanced/custom_loading.mjs +++ b/examples/advanced/custom_loading.js @@ -1,9 +1,9 @@ import { - create, - fractionDependencies, addDependencies, + create, divideDependencies, - formatDependencies + formatDependencies, + fractionDependencies } from '../../lib/esm/index.js' const config = { diff --git a/examples/advanced/custom_relational_functions.js b/examples/advanced/custom_relational_functions.js index fbcb2ab967..1558f381db 100644 --- a/examples/advanced/custom_relational_functions.js +++ b/examples/advanced/custom_relational_functions.js @@ -1,4 +1,4 @@ -const { create, all, factory } = require('../..') +import { all, create, factory } from '../../lib/esm/index.js' // First let's see what the default behavior is: // strings are compared by their numerical value diff --git a/examples/advanced/custom_scope_objects.js b/examples/advanced/custom_scope_objects.js index 2114d04491..d7c9823d2e 100644 --- a/examples/advanced/custom_scope_objects.js +++ b/examples/advanced/custom_scope_objects.js @@ -1,9 +1,9 @@ -const { create, all } = require('../..') +import { all, create } from '../../lib/esm/index.js' const math = create(all) -// The expression evaluator accepts an optional scope object. -// This is the symbol table for variable defintions and function declations. +// The expression evaluator accepts an optional scope Map or object that can +// be used to keep additional variables and functions. // Scope can be a bare object. function withObjectScope () { @@ -28,11 +28,11 @@ function withMapScope (scope, name) { math.evaluate('area(length, width) = length * width * scalar', scope) math.evaluate('A = area(x, y)', scope) - console.log(`Map-like scope (${name}):`, scope.localScope) + console.log(`Map-like scope (${name}):`, scope) } // This is a minimal set of functions to look like a Map. -class MapScope { +class CustomMap { constructor () { this.localScope = new Map() } @@ -61,7 +61,7 @@ class MapScope { * used in mathjs. * */ -class AdvancedMapScope extends MapScope { +class AdvancedCustomMap extends CustomMap { constructor (parent) { super() this.parentScope = parent @@ -91,25 +91,19 @@ class AdvancedMapScope extends MapScope { return this.localScope.clear() } - /** - * Creates a child scope from this one. This is used in function calls. - * - * @returns a new Map scope that has access to the symbols in the parent, but - * cannot overwrite them. - */ - createSubScope () { - return new AdvancedMapScope(this) - } - toString () { return this.localScope.toString() } } +// Use a plain JavaScript object withObjectScope() -// Where safety is important, scope can also be a Map -withMapScope(new Map(), 'simple Map') -// Where flexibility is important, scope can duck type appear to be a Map. -withMapScope(new MapScope(), 'MapScope example') -// Extra methods allow even finer grain control. -withMapScope(new AdvancedMapScope(), 'AdvancedScope example') + +// use a Map (recommended) +withMapScope(new Map(), 'Map example') + +// Use a custom Map implementation +withMapScope(new CustomMap(), 'CustomMap example') + +// Use a more advanced custom Map implementation +withMapScope(new AdvancedCustomMap(), 'AdvancedCustomMap example') diff --git a/examples/advanced/expression_trees.js b/examples/advanced/expression_trees.js index eaa956bd57..47ee87a84e 100644 --- a/examples/advanced/expression_trees.js +++ b/examples/advanced/expression_trees.js @@ -1,4 +1,4 @@ -const { parse, ConstantNode } = require('../..') +import { parse, ConstantNode } from '../../lib/esm/index.js' // Filter an expression tree console.log('Filter all symbol nodes "x" in the expression "x^2 + x/4 + 3*y"') diff --git a/examples/advanced/function_transform.js b/examples/advanced/function_transform.js index ae212f2178..82432c7773 100644 --- a/examples/advanced/function_transform.js +++ b/examples/advanced/function_transform.js @@ -6,7 +6,7 @@ * *transform* for the function. A transform is a function wrapping around a * function to be transformed or completely replaces a function. */ -const { create, all } = require('../..') +import { all, create } from '../../lib/esm/index.js' const math = create(all) // create a function diff --git a/examples/advanced/more_secure_eval.js b/examples/advanced/more_secure_eval.js index 46329ba7c3..6d4534fd74 100644 --- a/examples/advanced/more_secure_eval.js +++ b/examples/advanced/more_secure_eval.js @@ -18,7 +18,7 @@ // functionality, these functions can be disabled, as demonstrated in this // example. -const { create, all } = require('../..') +import { all, create } from '../../lib/esm/index.js' const math = create(all) const limitedEvaluate = math.evaluate diff --git a/examples/advanced/use_bigint.js b/examples/advanced/use_bigint.js deleted file mode 100644 index 79780fad90..0000000000 --- a/examples/advanced/use_bigint.js +++ /dev/null @@ -1,43 +0,0 @@ -// This example demonstrates how you could integrate support for BigInt -// in mathjs. It's just a proof of concept, for full support you will -// have to defined more functions and define conversions from and to -// other data types. - -const { create, all, factory } = require('../..') -const math = create(all) - -// we can also add conversions here from number or string to BigInt -// and vice versa using math.typed.addConversion(...) - -math.import([ - factory('BigInt', ['typed'], function createBigInt ({ typed }) { - typed.addType({ - name: 'BigInt', - test: (x) => typeof x === 'bigint' // eslint-disable-line - }) - - return BigInt // eslint-disable-line - }, { lazy: false }), - - factory('bigint', ['typed', 'BigInt'], function createBigint ({ typed, BigInt }) { - return typed('bigint', { - 'number | string ': (x) => BigInt(x) // eslint-disable-line - }) - }), - - factory('add', ['typed'], function createBigIntAdd ({ typed }) { - return typed('add', { - 'BigInt, BigInt': (a, b) => a + b - }) - }), - - factory('pow', ['typed'], function createBigIntPow ({ typed }) { - return typed('pow', { - 'BigInt, BigInt': (a, b) => a ** b - }) - }) -]) - -console.log(math.evaluate('4349 + 5249')) -console.log(math.evaluate('bigint(4349) + bigint(5249)')) -console.log(math.evaluate('bigint(4349) ^ bigint(5249)')) diff --git a/examples/algebra.js b/examples/algebra.js index 080c47d9ad..bd8b88ae87 100644 --- a/examples/algebra.js +++ b/examples/algebra.js @@ -3,9 +3,7 @@ // math.js has support for symbolic computation (CAS). It can parse // expressions in an expression tree and do algebraic operations like // simplification and derivation on this tree. - -// load math.js (using node.js) -const { simplify, parse, derivative } = require('..') +import { simplify, parse, derivative } from '../lib/esm/index.js' // simplify an expression console.log('simplify expressions') diff --git a/examples/basic_usage.js b/examples/basic_usage.js index 82af46df48..ae5b25d6ec 100644 --- a/examples/basic_usage.js +++ b/examples/basic_usage.js @@ -1,30 +1,45 @@ // basic usage - -// load math.js (using node.js) -const math = require('..') +import { + add, + atan2, + chain, + derivative, + e, + evaluate, + format, + log, + matrix, + multiply, + pi, + pow, + round, + sqrt, + subtract, + unit +} from '../lib/esm/index.js' // functions and constants console.log('functions and constants') -print(math.round(math.e, 3)) // 2.718 -print(math.atan2(3, -3) / math.pi) // 0.75 -print(math.log(10000, 10)) // 4 -print(math.sqrt(-4)) // 2i -print(math.pow([[-1, 2], [3, 1]], 2)) // [[7, 0], [0, 7]] -print(math.derivative('x^2 + x', 'x')) // 2 * x + 1 +print(round(e, 3)) // 2.718 +print(atan2(3, -3) / pi) // 0.75 +print(log(10000, 10)) // 4 +print(sqrt(-4)) // 2i +print(pow([[-1, 2], [3, 1]], 2)) // [[7, 0], [0, 7]] +print(derivative('x^2 + x', 'x')) // 2 * x + 1 console.log() // expressions console.log('expressions') -print(math.evaluate('1.2 * (2 + 4.5)')) // 7.8 -print(math.evaluate('12.7 cm to inch')) // 5 inch -print(math.evaluate('sin(45 deg) ^ 2')) // 0.5 -print(math.evaluate('9 / 3 + 2i')) // 3 + 2i -print(math.evaluate('det([-1, 2; 3, 1])')) // -7 +print(evaluate('1.2 * (2 + 4.5)')) // 7.8 +print(evaluate('12.7 cm to inch')) // 5 inch +print(evaluate('sin(45 deg) ^ 2')) // 0.5 +print(evaluate('9 / 3 + 2i')) // 3 + 2i +print(evaluate('det([-1, 2; 3, 1])')) // -7 console.log() // chained operations console.log('chained operations') -const a = math.chain(3) +const a = chain(3) .add(4) .multiply(2) .done() @@ -33,10 +48,10 @@ console.log() // mixed use of different data types in functions console.log('mixed use of data types') -print(math.add(4, [5, 6])) // number + Array, [9, 10] -print(math.multiply(math.unit('5 mm'), 3)) // Unit * number, 15 mm -print(math.subtract([2, 3, 4], 5)) // Array - number, [-3, -2, -1] -print(math.add(math.matrix([2, 3]), [4, 5])) // Matrix + Array, [6, 8] +print(add(4, [5, 6])) // number + Array, [9, 10] +print(multiply(unit('5 mm'), 3)) // Unit * number, 15 mm +print(subtract([2, 3, 4], 5)) // Array - number, [-3, -2, -1] +print(add(matrix([2, 3]), [4, 5])) // Matrix + Array, [6, 8] console.log() /** @@ -45,5 +60,5 @@ console.log() */ function print (value) { const precision = 14 - console.log(math.format(value, precision)) + console.log(format(value, precision)) } diff --git a/examples/bignumbers.js b/examples/bignumbers.js index bebc210fb3..29c882998d 100644 --- a/examples/bignumbers.js +++ b/examples/bignumbers.js @@ -1,8 +1,5 @@ -/* eslint-disable no-loss-of-precision */ - // BigNumbers - -const { create, all } = require('..') +import { create, all } from '../lib/esm/index.js' // configure the default type of numbers as BigNumbers const config = { diff --git a/examples/browser/lorenz.html b/examples/browser/lorenz.html new file mode 100644 index 0000000000..6919e1623a --- /dev/null +++ b/examples/browser/lorenz.html @@ -0,0 +1,73 @@ + + + + + + math.js | Lorenz Attractor + + + + + + + +
+ + + + \ No newline at end of file diff --git a/examples/browser/lorenz_interactive.html b/examples/browser/lorenz_interactive.html new file mode 100644 index 0000000000..8a8a1d7791 --- /dev/null +++ b/examples/browser/lorenz_interactive.html @@ -0,0 +1,193 @@ + + + + + + math.js | Lorenz Attractor + + + + + + + + + +
+
+
+ Inputs: + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + +
+ + + + + + + + + + + + +
+ + + +
+
+
+ + + + diff --git a/examples/browser/pretty_printing_with_mathjax.html b/examples/browser/pretty_printing_with_mathjax.html index 1fa273286f..d639b07d4a 100644 --- a/examples/browser/pretty_printing_with_mathjax.html +++ b/examples/browser/pretty_printing_with_mathjax.html @@ -5,7 +5,6 @@ math.js | pretty printing with MathJax -