Coder Social home page Coder Social logo

josdejong / mathjs Goto Github PK

View Code? Open in Web Editor NEW
14.0K 225.0 1.2K 89.52 MB

An extensive math library for JavaScript and Node.js

Home Page: https://mathjs.org

License: Apache License 2.0

JavaScript 98.28% HTML 0.04% MATLAB 0.04% Python 0.10% TypeScript 1.54%
math javascript complex-numbers matrices units bignumbers expression-evaluator

mathjs's Introduction

math.js

https://mathjs.org

Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser with support for symbolic computation, comes with a large set of built-in functions and constants, and offers an integrated solution to work with different data types like numbers, big numbers, complex numbers, fractions, units, and matrices. Powerful and easy to use.

Version Downloads Build Status Maintenance License FOSSA Status Codecov Github Sponsor

Features

  • Supports numbers, big numbers, 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.
  • Comes with a large set of built-in functions and constants.
  • Can be used as a command line application as well.
  • Runs on any JavaScript engine.
  • Is easily extensible.
  • Open source.

Usage

Math.js can be used in both node.js and in the browser.

Install math.js using npm:

npm install mathjs

Or download mathjs via one of the CDN's listed on the downloads page:

    https://mathjs.org/download.html

Math.js can be used similar to JavaScript's built-in Math library. Besides that, math.js can evaluate expressions and supports chained operations.

import {
  atan2, chain, derivative, e, evaluate, log, pi, pow, round, sqrt
} from 'mathjs'

// functions and constants
round(e, 3)                    // 2.718
atan2(3, -3) / pi              // 0.75
log(10000, 10)                 // 4
sqrt(-4)                       // 2i
pow([[-1, 2], [3, 1]], 2)      // [[7, 0], [0, 7]]
derivative('x^2 + x', 'x')     // 2 * x + 1

// expressions
evaluate('12 / (2.3 + 0.7)')   // 4
evaluate('12.7 cm to inch')    // 5 inch
evaluate('sin(45 deg) ^ 2')    // 0.5
evaluate('9 / 3 + 2i')         // 3 + 2i
evaluate('det([-1, 2; 3, 1])') // -7

// chaining
chain(3)
    .add(4)
    .multiply(2)
    .done()  // 14

See the Getting Started for a more detailed tutorial.

Browser support

Math.js works on any ES6 compatible JavaScript engine, including node.js, Chrome, Firefox, Safari, and Edge.

Documentation

Build

First clone the project from github:

git clone [email protected]:josdejong/mathjs.git
cd mathjs

Install the project dependencies:

npm install

Then, the project can be build by executing the build script via npm:

npm run build

This will build ESM output, CommonJS output, and the bundle math.js from the source files and put them in the folder lib.

Develop

When developing new features for mathjs, it is good to be aware of the following background information.

Code

The code of mathjs is written in ES modules, and requires all files to have a real, relative path, meaning the files must have a *.js extension. Please configure adding file extensions on auto import in your IDE.

Architecture

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.

The solution that mathjs uses has two main ingredients:

  • Typed functions. All functions are created using 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 numbers, 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.

  • 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.

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.

Implementing a new function

A common case is to implement a new function. This involves the following steps:

  • Implement the function in the right category, for example ./src/function/arithmetic/myNewFunction.js, where you can replace arithmetic with the proper category, and myNewFunction with the name of the new function. Add the new function to the index files ./src/factoriesAny.js and possibly ./src/factoriesNumber.js.
  • 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 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.
  • Ensure the code style is ok by running npm run lint (run npm run format to fix the code style automatically).

Build scripts

The build script currently generates two types of output:

  • any, generate entry points to create full versions of all functions
  • number: generating and entry points to create lightweight functions just supporting number

For each function, an object is generated containing the factory functions of all dependencies of the function. This allows to just load a specific set of functions, and not load or bundle any other functionality. So for example, to just create function add you can do math.create(addDependencies).

Test

To execute tests for the library, install the project dependencies once:

npm install

Then, the tests can be executed:

npm test

Additionally, the tests can be run on FireFox using headless mode:

npm run test:browser

To run the tests remotely on BrowserStack, first set the environment variables BROWSER_STACK_USERNAME and BROWSER_STACK_ACCESS_KEY with your username and access key and then execute:

npm run test:browserstack

You can separately run the code linter, though it is also executed with npm test:

npm run lint

To automatically fix linting issue, run:

npm run format

To test code coverage of the tests:

npm run coverage

To see the coverage results, open the generated report in your browser:

./coverage/lcov-report/index.html

Continuous integration testing

Continuous integration tests are run on Github Actions and BrowserStack every time a commit is pushed to github. Github Actions runs the tests for different versions of node.js, and BrowserStack runs the tests on all major browsers.

BrowserStack

Thanks Github Actions and BrowserStack for the generous free hosting of this open source project!

License

mathjs is published under the Apache 2.0 license:

Copyright (C) 2013-2024 Jos de Jong <[email protected]>

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 of the License at

   https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
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 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

mathjs's People

Contributors

bigfav avatar daniel-levin avatar dependabot-preview[bot] avatar dvd101x avatar ericman314 avatar firepick1 avatar fsmaxb avatar greenkeeper[bot] avatar guillermobox avatar gwhitney avatar harrysarson avatar honeybar avatar infusion avatar josdejong avatar josef37 avatar joshhansen avatar kv-kunalvyas avatar m93a avatar mattvague avatar morsecodist avatar nekomajin42 avatar patgrasso avatar rjbaucells avatar rnd-debug avatar saromanov avatar sebpiq avatar szechuansage avatar tetslee avatar thomasbrierley avatar veeloxfire avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mathjs's Issues

Even better chaining API

Right now you can do almost anything with chaining API, except something like :

math.ones(4).emultiply(0.6)

That would be nice if you could.

What about

math.select().ones(4).emultiply(0.6).done()

`subset` behaves strangely on edge cases and doesnt give helpful error messages

Some more strange behaviour

math.subset([[1, 2, 3, 4], [5, 6, 7, 8]], [math.range(0, 1), math.range(5, 4)]) // RangeError: Dimension mismatch (2 > 0)
math.subset([[1, 2, 3, 4]], [math.range(0, 0), math.range(5, 4)]) // [ [] ]

Error message that doesn't tell much :

math.subset([[0, 1, 1], [0, 5, 5]], [[0, 1], math.range(10, 1)]) // RangeError: Dimension mismatch (2 > 0)

Another wrong error message :

math.subset([[0, 1, 3], [9, 5, 6]], [[0, 1], math.range(0, 16)]) // RangeError: Index out of range (3 >= 3)

random(min, max) and randomInt(min, max)

Here is implementation for random and randomInt + some tests in mocha.
Sorry again, don't have time for making this clean and issuing a pull request.
If I do get time I'll do it!

var random = module.exports.random = function(min, max) {
  return min + Math.random() * (max - min)
}

module.exports.randomInt = function(min, max) {
  return Math.floor(random(min, max))
}

TESTS

  describe('random', function() {

    it('should pick values between min and max with a flat distribution', function() {
      var picked = []
        , count

      _.times(1000, function() {
        picked.push(utils.random(-10, 10))
      })

      count = _.filter(picked, function(val) { return val < -10 }).length
      assert.equal(count, 0)
      count = _.filter(picked, function(val) { return val > 10 }).length
      assert.equal(count, 0)

      count = _.filter(picked, function(val) { return val < -8 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val >= -8 && val < -6 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val >= -6 && val < -4 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val >= -4 && val < -2 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val >= -2 && val < 0 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val >= 0 && val < 2 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val >= 2 && val < 4 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val >= 4 && val < 6 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val >= 6 && val < 8 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val >= 8 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
    })

  })

  describe('randomInt', function() {

    it('should pick values between min and max with a flat distribution', function() {
      var picked = []
        , count

      _.times(1000, function() {
        picked.push(utils.randomInt(-15, -5))
      })

      picked.forEach(function(val) {
        assert.ok(_.contains([-15, -14, -13, -12, -11, -10, -9, -8, -7, -6], val))
      })

      count = _.filter(picked, function(val) { return val === -15 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val === -14 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val === -13 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val === -12 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val === -11 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val === -10 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val === -9 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val === -8 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val === -7 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
      count = _.filter(picked, function(val) { return val === -6 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)
    })

  })

Confusing it is that some functions return JS arrays other matrices

I find it sometimes hard to know which of Array or Matrix is returned.

I think it mostly comes from the fact that ones or zeros always return matrices, and then when an operation is applied to them, the result will always be a matrix.

I was doing all my calculations with arrays, and then, my result magically becomes a matrix because I have used ones somewhere.

One solution to make things clearer would be to have a strict mode where it would throw an error if you try to do :

math.emultiply(aMatrix, anArray)

It would force you to know what you are doing, and to always explicitely transtype your arrays/matrices which is a good thing for clarity and code maintainability.

Initialize parser scope

It would be nice if it were possible to initialize the scope of a parser instance, either by passing an object to the constructor, a scope setter method, or (preferably) both.

Proposal: complexPolar()

Would you be open to a function called e.g. complexPolar() which allowed one to construct a complex number using polar coordinates? math.complexPolar(r, theta) would be a quicker way of writing/executing (but otherwise equivalent to) math.multiply(r, math.exp(math.complex(0, theta))).

Support for typed arrays

Right now mathjs doesn't work with typed arrays. For example :

math.matrix([[1, 2, 3, 4]]).size() // [1, 4]
math.matrix([new Float32Array([1, 2, 3, 4])]).size() // [1]

Adding different values with different units

What I am interested in is adding values with different units. For example:

5 feet + 2 inches = 5.17 feet

So it would look something like this:
parser.eval('a = 5 feet + 2 inches').unit(a, 'foot') // "5.17 foot"

Or even better:
parser.eval('a = 5 feet + 2 inches').unit(a, 'foot', Number) // 5.17 (type is number instead of string)

Can this library do this? It looks like all of the pieces are there, but I can't put that together. Actually, I can't even get the basic examples on your site working properly:

I tried this:

parser.eval('a = 5.08 cm');
console.log(parser.eval('a in inch'));

I get this in the terminal:

{ value: 0.050800000000000005,
  unit: 
   { name: 'inch',
     base: {},
     prefixes: { '': [Object] },
     value: 0.0254,
     offset: 0 },
  prefix: { name: '', value: 1, scientific: true },
  hasUnit: true,
  hasValue: false,
  fixPrefix: true }

In your examples: parser.eval('2 inch in cm'); // 5.08 cm
the output of the parser looks like a simple string ("// 5.08 cm") but what I'm seeing is a json object.

Am I doing something wrong? Can this library add two values with different units?
thanks!

Switch code to 2 space indentation?

Most common code style in the node.js world is 2 space indentation. Though 4 space looks much more clear to me, it is maybe better to adhere to the standard code style.

math.multiply() not working as expected

math.select('3').done()
"3"
math.select('3').multiply(4).done()

TypeError: Function multiply(string, number) not supported
math.select('3').multiply("4").done()

TypeError: Function multiply(string, string) not supported

Am I doing something wrong?

integration and differentation

Hi,
is it possible to add integrals and differentials to the library?
Or maybe it already is added, but I didn't spot it.

The greatest common divisor

Would be pretty useful to have gcd implementation. Also the least common divisor would be calculated as: a * b / math.gcd(a, b);

function to solve equations

I don't know if this is in the scope of this project but it would be great to have a solve function.

Something like this:

x = solve(f = x + 1, x) 

where x will become:

x =  f - 1 

I will try to accomplish this by myself if I have to.
Thanks for this awesome library!

0.1 + 0.2 is not 0.3

I was playing around with your library, which is great by the way. I've noticed some inconsistencies from what I've seen on your website and what I get when I use the library. See the following screenshot. I've experienced the same thing in Chrome Canary, IE10, and Firefox latest.

http://twitpic.com/d3tbxq

pickRandom for picking value in a array (with optional weight)

I don't have time to make a proper fork + pull request, but here is a simple implementation + tests if you're interested :

Implementation

module.exports.pickRandom = function(possibles, weights) {
  var val = Math.random()
    , acc = 0
    , i

  // If weights is not given we create an array of equiprobable weights
  if (!weights) {
    var length
    weights = []
    for (i = 0, length = possibles.length; i < length; i++)
      weights.push(1/length)
  }

  // Pick the value from possibles
  i = -1
  while(val > acc) {
    i++
    acc += weights[i]
  }
  return possibles[i]
}

Tests (using mocha and underscore)

  describe('pickRandom', function() {

    it('should pick values equiprobably', function() {
      var possibles = [11, 22, 33, 44, 55]
        , picked = []
        , count

      _.times(1000, function() {
        picked.push(utils.pickRandom(possibles))
      })

      count = _.filter(picked, function(val) { return val === 11 }).length
      assert.equal(math.round(count/picked.length, 1), 0.2)

      count = _.filter(picked, function(val) { return val === 22 }).length
      assert.equal(math.round(count/picked.length, 1), 0.2)

      count = _.filter(picked, function(val) { return val === 33 }).length
      assert.equal(math.round(count/picked.length, 1), 0.2)

      count = _.filter(picked, function(val) { return val === 44 }).length
      assert.equal(math.round(count/picked.length, 1), 0.2)

      count = _.filter(picked, function(val) { return val === 55 }).length
      assert.equal(math.round(count/picked.length, 1), 0.2)
    })

    it('should pick values with the given distribution', function() {
      var weights = [0.1, 0.2, 0.7]
        , possibles = [11, 22, 33]
        , picked = []
        , count

      _.times(1000, function() {
        picked.push(utils.pickRandom(possibles, weights))
      })

      count = _.filter(picked, function(val) { return val === 11 }).length
      assert.equal(math.round(count/picked.length, 1), 0.1)

      count = _.filter(picked, function(val) { return val === 22 }).length
      assert.equal(math.round(count/picked.length, 1), 0.2)

      count = _.filter(picked, function(val) { return val === 33 }).length
      assert.equal(math.round(count/picked.length, 1), 0.7)
    })

  })

2.3*(3+--4) gives "SyntaxError: Value expected (char 9)"

2.3_(3+--4) gives "SyntaxError: Value expected (char 9)" in Math Notepad.
this doesn't seem to handle the case where a number has multiple unary signs. unfortunate as the case may be. in math, we know that this may be the case.
this should effectively be parsed as 2.3_(3+(--4)) if you were to put perens in everything and group the unary ops.

Automatically squeeze matrices when indexing with a float

Slicing should squeeze the matrices automatically. For example :

var m = math.matrix([[1, 2, 3], [4, 5, 6]])
m.get([0, math.range(0, 2)]) // [ [ 1, 2, 3 ] ]

Should be

var m = math.matrix([[1, 2, 3], [4, 5, 6]])
m.get([0, math.range(0, 2)]) // [ 1, 2, 3 ]

Ranges and matrix indexing should exclude upper bound [a, b)

A very common case for ranges is to get the whole content of an array / matrix, which is zero based. So currently you would do :

myMatrix.get([math.range(4, 7), math.range(0, myMatrix.size()[1] - 1)])

Ranges functions I can think of (Python, numpy, underscore) don't include the last step of the range, which is more convenient for this use-case when the array/matrix is zero-based, and which is consistent with a for loop :

myMatrix.get([math.range(4, 8), math.range(0, myMatrix.size()[1])])

So is it a conscious choice to include the last step IN the range ( [start, end] instead of [start, end[) while usually it is not the case?

Proposal: design API with performance in mind

Have you considered making performance/speed an explicit goal of math.js? For instance, if you were to require all matrices to have all numbers of a specified type (as e.g. numpy does), then you could in the future use typed arrays or even call into BLAS libraries using node-ffi to gain additional performance advantages. It will require some API changes, but could very well be worth it. Even if we don't work directly on performance at the moment, refactoring parts of the API in ways that would allow them to be implemented with high performance could be quite useful in preparing for future growth.

json serialization formats for Complex, Matrix, etc

This may very well be beyond the scope of this project, but I bring it up here because you may be interested or have valuable feedback to give.

It would be very nice if there were a way to serialize e.g. a mathjs Matrix of complex numbers into json, and then unserialize it. This would allow for e.g. communication of a matrix in its entirety between a server running nodejs and a client.

This would require a custom method of serializing these types into json objects, but that should not be difficult. The harder thing is to settle on such a method. I've looked a bit into how others have handled this and have found very little. The Python documentation, for instance, defines custom json encoders and decoders for complex numbers, but it does not even use the same format for encoding and decoding! So it seems to be purely a hypothetical example, and not an actual example meant to be used.

One way of storing a complex number could be something like

{
    "mathjson": "complex",
    "real": 3,
    "imag": 4
}

A matrix could then be stored like

{
    "mathjson": "matrix",
    "data": [[1, 2], [3, 4]]
}

A mathjs function could then exist that takes a decoded json object and recursively turns it and its referenced objects into their corresponding mathjs objects by searching each object for a "mathjson" field.

Thoughts?

Should Parser.parse throw 'Undefined symbol' error?

Just wondered if the parse method of Parser should throw an 'Undefined symbol' error. At the moment if you parse something like:

sinx

where the brackets are omitted around the x, there is no error until eval is called on the node tree. It would be nice to know if an expression like this was invalid without having to call eval.

different abbreviations for trigonometric functions

It would be nice, if user could use not only tan() and cot() for corresponding trigonometric functions, but also tg() and ctg(). And maybe tag(), tang(), cotan() and cotg(). The first two are usually used in West and Central Europe, and the four latter are also sometimes encountered in various sources.
In far West side of Europe there is also used sen() as sinus function abbrev.

matrices broken in release .10.0?

Installed mathjs using npm, so got version 0.10.0
var math = require('mathjs');

and attempted to create a matrix using:
var m = new math.matrix([[1,1],[1,1]]);

received error on unsupported data type (Array).
TypeError: Unsupported type of data (array)
| at new Matrix (/home/ubuntu/node_modules/mathjs/math.js:1053:15)
| at Object.matrix (/home/ubuntu/node_modules/mathjs/math.js:7639:12)
| at getSystemTransferMatrix (repl:1:1567)
| at new System (repl:1:489)
| at repl:1:11
| at REPLServer.self.eval (repl.js:112:21)
| at repl.js:249:20
| at REPLServer.self.eval (repl.js:122:7)
| at Interface. (repl.js:239:12)
| at Interface.EventEmitter.emit (events.js:95:17)

after several hours, uninstalled v.10 and installed v0.8.1. Not sure if that fixed it or not.

I looked at the source code for 0.10.0 and it looked okay, so I'm stumped.

splice-like function

subset is close to that, but you can't actually remove a subset from the initial matrix.

Is it possible to add to the unary operator ! for factorial to the parser?

Perhaps this request is based out of ignorance. However, I would like to see the parser recognize expressions like 5!

I realize the default usage for ! is a logical operator within JS but does this prevent the parser from reading such an expression and calling the factorial function?

Please let me know your thoughts! I truly am at a loss on this issue.

Thanks!

Kaleb

Add function "npm test".

I think it is better support "npm test".

$ npm test

> [email protected] test /Users/youichikato/github/mathjs
> tap test/**/*.js

ok test/function/arithmetic.js .......................... 1/1
ok test/function/complex.js ............................. 1/1
ok test/function/probability.js ......................... 1/1
ok test/function/statistics.js .......................... 1/1
ok test/function/trigonometry.js ........................ 1/1
ok test/function/units.js ............................... 1/1
ok test/type/complex.js ................................. 1/1
ok test/type/unit.js .................................... 1/1
total ................................................... 8/8

To supporting "npm test", I need little change in package.json.

$ git diff package.json
diff --git a/package.json b/package.json
index a3987fc..91a1e28 100644
--- a/package.json
+++ b/package.json
@@ -30,10 +30,13 @@
         "jake": ">= 0.5.8",
         "uglify-js": ">= 2.2.5",
         "nodeunit": ">= 0.7.4",
-        "dateable": ">= 0.1.2"
+       "dateable": ">= 0.1.2",
+       "tap": ">=0.4.0"
     },
     "scripts": {
-        "prepublish": "jake"
+        "preinstall": "npm install -g jake tap",
+        "prepublish": "jake",
+       "test": "tap test/**/*.js"
     },
     "main": "./math.js",
     "engines": {

Also, plead add ./.travis.yml, because numbers.js has ./.travis.yml.

Thanks,

Incorporate with regression.js

I love your program and was using it a lot in my code but i also needed to do a regression analysis. Its only one more script src but i found a great library at https://github.com/Tom-Alexander/regression-js that works perfectly. I also saw that you program(rightly so) has a much bigger user database. I thought it would be a good combination if you made a sort of pull request(i realize that maybe it would make your code much larger but its just a thought. maybe even just a footnote under your statistics tab in the readme)

Thanks

Write test cases

The tests are all organized in files which is great, but as the library grows it would probably be better to use a proper testing framework, and writing separate test cases.
I suggest mocha. I think it is pretty simple and gets the job done really well.

FFT functions

I don't know if that stays in the scope of mathjs.
If you're interested I can implement them.

one-based used for matrix indices should be documented and justified

Unlike many matrix libraries in C-like languages which use zero-based indices, and unlike javascript arrays, the matrices in math.js use one-based indices, such that the top-left-most element is labeled [1, 1]. At a minimum, this should be mentioned in the README and justified.

Even better from my perspective would be to use zero-based indices in the first place, but I suppose you must have decided on one-based indices for a reason, and it would likely be hard to convince you to change at this point...

Evaluations with i

Hi, it appears that eval() has some troubles with expressions that include i, such as "i^2" and "i/0". Strangely, "i^2" doesn't return "-1" (although a number that is very close), but "i*i" does. "i/0" returns "0" but should return "infinity".

Also, a small secondary note, I believe the term complex infinity is preferable for division with zero rather than just infinity.

juxtaposition for multiplication

Hi
I was wondering, if it is possible to add functionality which allows to guess, where should be multiply sign.
For now, AFAIK, we need to write all multiply signs explicitly, e.g.:

2_sin(x), or cos(2_x), or 2_x + 5, or sin(x)_cos(x), etc.

It would be nice, if it was possible, to write those expressions in the following way:

2sin(x), cos(2x), 2x + 5, sin(x)cos(x)

Derived units (e.g. 1m/1s =1m/s)

Hi,
I must say I am really impressed by this library! I toyed around a bit with the parser and one thing that I thought would be very powerful was if different units could be calculated. e.g.

a = 1s
b= 1m
c = b/a (currently throws an error but would be cool if it could return 1 m/s)

Is this something you plan on supporting? If you could provide some guidelines on how this could be implemented I could give it a try (not super skilled in javascript but stubborn ;) )

Chai plugin for approximate assertions (ex : 4 ~ 3.99)

Write a chai plugin for the tests, which handles approximations.

We probably need :

assertApproxEqual(4, 3.99, 0.01) // val, testval, tolerance
assertDeepApproxEqual([4, 3], [3.99, 2.98], 0.02) // val, testval, tolerance

Switching to grunt for tasks?

Just a suggestions. A bunch of the tasks that are written in the Jakefile are handled by some grunt modules, so it would save a bit of code.

Plus jake gives me weird errors when trying to build the dist :

Error: EMFILE, open '/Users/spiq/Documents/mathjs/package.json'

Should range be used to generate arrays?

I am not convinced with the range object. I think the main use case for it is slicing, so it should be slice.

In numpy slice and ranges are different. In fact there is no range. There is 2 functions linspace and arange, which just return a matrix. My opinion is that it should work the same here.

range is convenient enough to generate a range start:step:end, but it is not convenient if you want to generate "N points equally spaced between A and B". This is what linspace and arange are for. 2 ways to generate a range.

So my suggestion, reserve range for slicing, reflect this by renaming it slice, and add 2 functions to generate "range matrices"

For example, I got this today :

math.range(-1, 1.0 + 2/(winSize - 1), 2/(winSize - 1)).toArray().length // 1025
math.range(-1, 1.0 + 2/(winSize - 1), 2/(winSize - 1)).size() // [1024]

Very large numbers

It appears that the handling of very large numbers is suboptimal. "5^5^5" (or "5^3125") is evaluated as infinity, for example. I am aware that it's a huge number, "1.911012597945477520356404559703964599198081048 × 10^2184", but still, it seems to me like it should just respond with "Error: Too big number" or something like that. Preferably without breaking the infinity evaluation of things like division with zero.

You'll probably be seeing much of me here since I just built a little something using Math.js here. I might also start contributing to this project in the future. I'd like to take the chance to say that I really love this library and am very grateful for its existence before you start seeing me as an annoying nitpicker. Thanks!

CSS colors

How reasonable would it be to support color math and conversions? It seems like colors could conceivably be another unit. Something like:

#FF0000 in rgb

hsl(10, 20, 30) + rgb(100, 10, 25)

Does that seem doable and reasonable, or just completely insane? ;)

Problem with unequal ?

Hello,

I suppose the code for unequal should be as follows.

Best regards.

/**
 * Check if value x unequals y, x != y
 * In case of complex numbers, x.re must unequal y.re, or x.im must unequal y.im
 * @param  {Number | Complex | Unit | String | Array | Matrix | Range} x
 * @param  {Number | Complex | Unit | String | Array | Matrix | Range} y
 * @return {Boolean | Array | Matrix} res
 */
math.unequal = function unequal(x, y) {
    if (arguments.length != 2) {
        throw newArgumentsError('unequal', arguments.length, 2);
    }

    if (isNumber(x)) {
        if (isNumber(y)) {
            return x != y;
        }
        else if (y instanceof Complex) {
            return (x != y.re) || (y.im != 0);
        }
    }

    if (x instanceof Complex) {
        if (isNumber(y)) {
            return (x.re != y) || (x.im != 0);
        }
        else if (y instanceof Complex) {
            return (x.re != y.re) || (x.im != y.im);
        }
    }

    if ((x instanceof Unit) && (y instanceof Unit)) {
        if (!x.equalBase(y)) {
            throw new Error('Cannot compare units with different base');
        }
        return x.value != y.value;
    }

    if (isString(x) || isString(y)) {
        return x != y;
    }

    if (x instanceof Array || x instanceof Matrix || x instanceof Range ||
        y instanceof Array || y instanceof Matrix || y instanceof Range) {
        return util.map2(x, y, math.unequal);
    }

    if (x.valueOf() !== x || y.valueOf() !== y) {
        // fallback on the objects primitive values
        return math.unequal(x.valueOf(), y.valueOf());
    }

    throw newUnsupportedTypeError('unequal', x, y);
};

Change build system to browserify

Right now all the files are concatenated into one big file which is rather ugly, and really not convenient for testing nor debugging ...
Plus you don't see where the functions are imported from as there is no call to require, which makes it rather inconvenient to read the code quickly.

Browserify allows to write your module exactly the way you would do in Node, with require. I believe it would be a 30 minutes - 1h work. So it's no big deal.
Only thing to do is add calls to require, and add an index.js file which exposes the public API.

Random functions do not accept a matrix as input

The random functions random, randomInt, and pickRandom do not accept matrices as input for size or possibilities, for example:

math.random(math.matrix([2,3]))
math.randomInt(math.matrix([2,3]))
math.pickRandom(math.matrix([1,2,3,4,5]))

I would expect them to output an Array if size was and Array, and output an Matrix if size was a Matrix, same with possibilities for pickRandom.

An an other thing: pickRandom always uses a uniform distribution, also when you have created a normal distribution object. Is that intentionally or a bug?...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.