bugwheels94 / math-expression-evaluator Goto Github PK
View Code? Open in Web Editor NEWMath JS library. Super advanced & efficient Math expression evaluator
License: MIT License
Math JS library. Super advanced & efficient Math expression evaluator
License: MIT License
Hello!
There seems to be a bug when you write 0.5sin(1)
instead of 0.5*sin(1)
, which leads to the page freezing with memory leaks and eventually runs out of memory.
To reproduce:
print("0.5sin(5)")
It would be simply wonderful to get support for doing math evaluations using hexadecimal (or even octal) notation. Is there any way to do add that?
We would like to use the math-expression-evaluator for a calculator input field which only needs basic math operations (addition, subtraction, multiplication and divison). Is there a possibility to "whitelist" the allowed operations only?
mexp.eval("89*0.11") -> 9.790000000000001 error
correct : 89*.011 = 9.79
Can it support the operation of √?
such as:
console.log(mexp.eval("√2*√5"));
mexp.eval sin10
:
0.17364817766693
vs
JS Math.sin(10)
:
-0.5440211108893698
Why is it like that?
-3^2 = 9 Should evaluate to -9
note: (-3)^2 should evaluate to 9
When I run tsc --noEmit
in my project with the installed latest version of the math-expression-evaluator
(2.0.0) and TypeScript version 4.9.4, it shows me that there are some syntax errors in the dist
folder of the library, seemingly because there's missing type
keyword in the export
statements:
node_modules/math-expression-evaluator/dist/types/postfix_evaluator.d.ts:2:1 - error TS1128: Declaration or statement expected.
2 export Constants = Record<string, number>;
~~~~~~
node_modules/math-expression-evaluator/dist/types/token.d.ts:2:1 - error TS1128: Declaration or statement expected.
2 export Token = {
~~~~~~
node_modules/math-expression-evaluator/dist/types/token.d.ts:3:21 - error TS1005: ',' expected.
3 type: tokenTypes;
~
node_modules/math-expression-evaluator/dist/types/token.d.ts:4:15 - error TS1005: ',' expected.
4 value: any;
~
node_modules/math-expression-evaluator/dist/types/token.d.ts:5:18 - error TS1005: ',' expected.
5 token: string;
~
node_modules/math-expression-evaluator/dist/types/token.d.ts:6:31 - error TS1005: ',' expected.
6 numberOfArguments?: number;
~
node_modules/math-expression-evaluator/dist/types/token.d.ts:7:17 - error TS1005: ',' expected.
7 show: string;
~
node_modules/math-expression-evaluator/dist/types/token.d.ts:8:23 - error TS1005: ',' expected.
8 precedence: number;
~
node_modules/math-expression-evaluator/dist/types/token.d.ts:10:1 - error TS1128: Declaration or statement expected.
10 export ParsedToken = Omit<Token, 'token'> & {
~~~~~~
node_modules/math-expression-evaluator/dist/types/token.d.ts:11:18 - error TS1005: ',' expected.
11 hasDec?: true;
~
Found 10 errors in 2 files.
Errors Files
1 node_modules/math-expression-evaluator/dist/types/postfix_evaluator.d.ts:2
9 node_modules/math-expression-evaluator/dist/types/token.d.ts:2
This breaks the type checking of the code using the library.
Maybe it's something to do with how the types are built, e.g. on this line?
Could you please help me understand how to fix it? I could create a PR to remove the replacement of export type
to export
, but I'm unsure whether it will introduce any breaking changes or regressions.
I am trying to convert a number nagative to positive under root function. I register a custom token name positive who handle calculation.
my token is { type: 0, token: 'positive', show: 'positive', value: function (a) { return Math.abs(a); } }
when my formula is "positive(2-6)" is calculate fine and give me result 4.
but when my formula is "root(positive(2-6))" is not throw error but the result is NaN.
Hello, sir. Here is a problem:
const Mexp = require('math-expression-evaluator');
const math = new Mexp();
console.log( math.eval(`44.23 + 65.53`) );
We expect the result is 109.76;
However, the result is still 109.75999999999999 .
We hope it will be fixed. I look forward to hearing from you soon.
Thx. Best wishes.
After reading the readme I think you miss Math.abs
🤔
My use case
mexp.eval(
"|$x| > $y"
.replace("$x", x)
.replace("$y", y)
)
mexp.eval("sin(pi/2)") returns 0.027412133592044
was expecting 1
Hi,
I use this package as a dependancy of cssnano in a Gulp build task from the command line. After a recent update, the build task has started producing a lot of unexpected output (~150 lines) every time cssnano runs.
I've narrowed it down to the console.log
statement below. Is this something that could be disabled, perhaps with CLI flags?
math-expression-evaluator/src/lexer.js
Line 181 in da0d032
Someone pointed out to me that the source directory is published to npm. Don't do that as it's not used by anything and is bloat.
Hey I just started using your library recently for rather regular evaluations that have a simple answer, but now i kind of just added a figure system that takes the figures off the server and makes them countable using a stringified code that comes from the server response.
const figureItem: Token[] = figureTokens.map(figure => ({
type: 6,
value: figure.result,
token: figure.code,
show: figure.code,
precedence: 6
}));
try {
const value = newStatement ? mexp.eval(newStatement, figureItem, {}) : undefined;
return {
statement: newStatement,
acreage: value !== undefined ? value : 0,
statementIsValid: true,
};
}
Here is the log from the figureItem.
precedence: 0
show: "s3921839"
token: "s3921839"
type: 6
value: 30
What I basically want this thing to do is that when the newStatement is 5+5+ "s3921839"(userwritten figure code) I want the evaluation to be 40.
If you could help id be very grateful thank you !
[email protected] is using webpack@5 as dependency, It may cause build error in some project using webpack@4
Should be: lne^2 = ln(e^2) = 2. Not lne^2 = (lne)^2 = 1
Also: log10^2 = log(10^2)=2. Not log10^2 = (log10)^2 = 1
Simple expressions such as 1/-1 or 1*-1 can not be evaluated.
Cannot read properties of undefined (reading 'value')
1) Testing Unit dividing by negative number :
TypeError: Cannot read properties of undefined (reading 'value')
at t.w [as postfixEval] (C:\Users\pierr\git\contribs\web\math-expression-evaluator\dist\es\index.js:1:6463)
at t.eval (C:\Users\pierr\git\contribs\web\math-expression-evaluator\dist\es\index.js:1:10931)
at Context.<anonymous> (C:\Users\pierr\git\contribs\web\math-expression-evaluator\test\index.js:183:21)
at callFn (C:\Users\pierr\git\contribs\web\math-expression-evaluator\node_modules\mocha\lib\runnable.js:326:21)
at Test.Runnable.run (C:\Users\pierr\git\contribs\web\math-expression-evaluator\node_modules\mocha\lib\runnable.js:319:7)
at Runner.runTest (C:\Users\pierr\git\contribs\web\math-expression-evaluator\node_modules\mocha\lib\runner.js:422:10)
at C:\Users\pierr\git\contribs\web\math-expression-evaluator\node_modules\mocha\lib\runner.js:528:12
at next (C:\Users\pierr\git\contribs\web\math-expression-evaluator\node_modules\mocha\lib\runner.js:342:14)
at C:\Users\pierr\git\contribs\web\math-expression-evaluator\node_modules\mocha\lib\runner.js:352:7
at next (C:\Users\pierr\git\contribs\web\math-expression-evaluator\node_modules\mocha\lib\runner.js:284:14)
at Immediate._onImmediate (C:\Users\pierr\git\contribs\web\math-expression-evaluator\node_modules\mocha\lib\runner.js:320:5)
at processImmediate (node:internal/timers:466:21)
The documentation here has some typos
in the supported math symbols section,
\ Multiplication Operator eg. 23 results 6
should be
* Multiplication Operator eg. 2*3 results 6
in the Adding token using constituents of eval method of mexp object section,
"lex
method takes list of tokens as explained here as second second arguments"
should be
"lex
method takes list of tokens as explained here as second second arguments"
in the Adding tokens using eval method of mexp object section,
var value = =mexp.eval(exp,[token1,token2,...],pair);
should be
var value = mexp.eval(exp,[token1,token2,...],pair);
in the Functions with two parameters section,
the phrase "two number/argument" should be "two numbers/arguments", as well as in Functions with three parameters
2^-1 - this works in online playground - v. 2.0.1
2^-1 - this does not work in v 2.0.4/5 -> error
2^(-1) - this works in v 2.0.4/5
2^(2*-1) - this does not work in v 2.0.4/5 -> error
Error: TypeError: Cannot read properties of undefined (reading 'value')
@ankit31894 Last commit indexOf
broke a lot of projects.
Now it works, but I would suggest you to use for instance lodash.indexof
instead of your patched code, because this code is well tested.
Please be more semver compatible.
2.0.1+ is breaking, no docs either yet, existing tokens must have a precedence value. I propose adding defaults to match old behaviour?
I created 2 custom functions
{
type: 0,
token: "ceil",
show: "ceil",
value: function (a) {
return Math.ceil(a);
},
},
{
type: 8,
token: "min",
show: "min",
value: function (a, b) {
return Math.min(a, b);
},
independtly they works fine, but when I try this
min( 4, ceil (0.011 * 100))
I don't obtain the right value I obtain 4 and not 2
Thanks for your help and this great project
Steps to reproduce:
npx degit sveltejs/template my-svelte-project
cd my-svelte-project
npm install
npm install math-expression-evaluator
import mexp from 'math-expression-evaluator'
to App.sveltemexp.eval
in App.sveltenpm run dev
Result:
Uncaught ReferenceError: assignment to undeclared variable i
tokenize lexer.js:162
lex lexer.js:230
eval postfix_evaluator.js:93
create_fragment$2 App.svelte:15
init index.mjs:1486
App bundle.js:2678
app main.js:3
<anonymous> bundle.js:2697
Disabling strict helps:
Setting the optionoutput.strict to false in rollup.config.js
Can math-expression-evaluator be adaptable to JS strict mode?
Does it possible to make mexp.eval("1 2"); throw error instead of result equal to 1 2
Thanks
Suggest removing the code:
return parseFloat(stack[0].value.toFixed(15))
from src/postfix_evaluator.ts
because it only partially solves the issue floating point math, and because there are better work-arounds.
The following code demonstrates both that floating point issues exist, and also that the addToken functionality already allows end-users to fix the issue according to their needs.
import Mexp from './dist/index.js';
import Big from 'big.js';
var mexp = new Mexp();
console.log(mexp.eval('.1 + .2')); // 0.3
console.log(mexp.eval('5.33 + 5.2')); // 10.530000000000001
mexp.addToken([{
type:2,
token:"+",
show:"+",
value:function(a,b){
return Big(a).plus(b).toNumber();
}
}])
console.log(mexp.eval('.1 + .2')); // 0.3
console.log(mexp.eval('5.33 + 5.2')); // 10.53
I discovered this bug with basic division when there is a bracket set involved.
The solution to 55/(.07-.04) = 1375, but returns 1374.999...8
I have prepared breaking tests in the following fork/branch
https://github.com/givethemheller/math-expression-evaluator/tree/heller/odd-paren-behavior
I'm unsure if this issue should go here or in the Definitely Typed repo.
According to the types eval
returns a string:
static eval(exp: string, tokens?: Token[], pair?: object): string;
I managed to find that this repo returns a string for "Infinity" here: postfix_evaluator.js
Shouldn't the return type then be number | string
?
Will eval
return a string for any other cases?
If not, perhaps we could change eval
to return the global Infinity number?
Then the types at Definitely Typed could be change to have eval
return number
By default functions with or without parentheses evaluate to the correct result. Can we add an option to require parentheses for evaluation otherwise the function would fail?
Hello. Please look at next code:
mea.eval('root(4-(2-1)^2)'); // 3
mea.eval('root(4-1^2)'); // 1.732050807568877
mea.eval('(4-(2-1)^2)^.5'); // 1.732050807568877
Since you want cos0=cos(0)=1, you should make it to return cos-0=cos(-0)=1. But your program returns cos-0-cos0=cos(-0-cos(0))=cos(-1) != 0. You should correct it, to return cos-0-cos0=cos(-0)-cos(0)=1-1=0.
The same case for other functions, even log and ln.
Awesome library. Using it for user-definable math and some custom tokens, it's really useful and powerful. Recently I've come to an issue where I want to have a 5-input token, for example:
function scale_number(unscaled, to_min, to_max, from_min, from_max) {
return (to_max-to_min)*(unscaled-from_min)/(from_max-from_min)+to_min;
}
I couldn't implement a version of that. Could you perhaps add support for more control over defining tokens?
It returns -6. It should return -9.
Also -3^(1+1) returns -4. It should return -9. But 0-3^(1+1) return correct answers. (The same for the first example)
I am trying add a formula token like
max(1,2,3,4,5) which will show 5
or min(2,5,6,8,1) which will show 1
Any way to implement these types of tokens.
Here I am again, with my obscure usage of your awesome library haha.
So, recently I bumped it to the latest version, about 3 weeks ago if my memory serves me. Ever since a couple users of my site have noticed a problem with math automations - they start to lag massively with the growing amount of calls to Mexp.
I have been able to reproduce the issue on your JSBin too, replace the script tag with my code, and open the performance monitor in devtools and you will be able to see it. Be careful however, it may crash the tab.
<script>
const mexp = new Mexp()
function yourFunction(){
// do whatever you like here
print("2+1")
print("2+2")
print("2+3")
print("2+4")
print("2+5")
print("2+6")
print("2+7")
print("2+8")
setTimeout(yourFunction, 17);
}
yourFunction();
function print(str){
document.body.appendChild(document.createTextNode(str+" evaluates to "+mexp.eval(str)));
document.body.appendChild(document.createElement("hr"));
}
</script>
This has not happened before to my knowledge, so some commit has introduced this bug. I'd really appreciate it if you could look into it soon, since a lot of user-generated stuff on my site is using Mexp and it would be quite annoying if most projects start lagging within 30 seconds of playing.
P.S. Live example :). Ignore the ugly visuals haha. Press the play button, and observe the update time counters gradually rising as the song is playing. The calculations are all very simple multiplications, and there are 6 of them. It's the equivalent of running the code I sent above, in terms of Mexp.
It'd be a major bump, but it'd make math-expression-evaluator
free of dependencies.
At the line located here, an arbitrary decision is decided to return a value of infinity when the number exceeds 10^15
Could this be configurable in the evaluate function? Could it just be eliminated? There's plenty of calculations where numbers greater than 10^15 would be part of the equation. Whats the reason for the infinity return?
It would be great to support conditional expressions (like "if statements").
Similar to math.js "Conditional expression" seen here
https://mathjs.org/docs/expressions/syntax.html
In my TypeScript source code I wrote the following:
import Mexp from 'math-expression-evaluator';
const mexp = new Mexp();
tsc outputs this:
const math_expression_evaluator_1 = require("math-expression-evaluator");
const mexp = new math_expression_evaluator_1.default();
I get the following error when trying to run the script:
const mexp = new math_expression_evaluator_1.default();
^
TypeError: math_expression_evaluator_1.default is not a constructor
Url of script in example does not exist: http://redhivesoftware.com/calculators/math-expression-evaluator.min.js
Hi there,
Currently, if a user defines a token (e.g. a variable) as E
, it will be overwritten by Math.E
. What do you think about preventing this overwrite if a user-defined token of the same name is provided?
Cheers
I'm having difficulty registering tokens. I am creating a number of tokens dynamically and attempting to add them to mexp. I have gotten very simple cases to work correctly, but any actual use case is triggering an error. No matter whether I use the addToken
method or through eval
directly, I always get the error Cannot read property 'length' of undefined at Function.push.f7Mu.Mexp.addToken (lexer.js:72)
(eval
method is slightly different stack trace but same error)
My token and value fields are unique per token and I am pushing the correct pairs to match up with my tokens. Are there any conditions that I'm missing or which are undocumented? Could it be that my token/value have numeric digits in them?
Thanks for the help
Some anchor links miss the # and I can't find the source repo to pull request.
Just wanted to let you know I raised a PR that was recently merged to the DT project, adding TypeScript definitions for this package, I'm assuming this is fine?
Would be amazing if you could support percentages
mxp.eval('10% + 40%')
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.