Parse Math ExpressionHow would I manually (no third-party libraries) evaluate an equation from a string in C#?Double.TryParse doesn't allow to use divisions (fractions) as inputC# - Load Mathematical FormulaConvert string into mathematical expressionFunction of count / process a series of combination numbers and math operations ('+', '-', '*", '/')Equation (expression) parser with precedence?Is there a string math evaluator in .NET?operators as stringsBest Free C# Math Parser using variables, user defined functions, custom operatorsDoing math in vb.net like Eval in javascriptBest way to parse command line arguments in C#?Replacing .NET WebBrowser control with a better browser, like Chrome?Parse JSON in C#Reflecting parameter name: abuse of C# lambda expressions or Syntax brilliance?Boolean and Math Expression ParserSimple state machine example in C#?Curious null-coalescing operator custom implicit conversion behaviourWhy is processing a sorted array slower than an unsorted array?Why not inherit from List<T>?Found conflicts between different versions of the same dependent assembly that could not be resolved
What is Plautus’s pun about frustum and frustrum?
Why was Thor doubtful about his worthiness to Mjolnir?
Surely they can fit?
How to make a language evolve quickly?
How to compact two the parabol commands in the following example?
How does noise-cancellation work in Mac laptops?
How to minimise the cost of guessing a number in a high/low guess game?
Python Pandas Expand a Column of List of Lists to Two New Column
Why do Thanos's punches not kill Captain America or at least cause some mortal injuries?
How did Thanos not realise this had happened at the end of Endgame?
Why doesn't Rocket Lab use a solid stage?
How to select certain lines (n, n+4, n+8, n+12...) from the file?
Usefulness of complex chord names?
Should these notes be played as a chord or one after another?
Why was Endgame Thanos so different than Infinity War Thanos?
Ex-manager wants to stay in touch, I don't want to
Anatomically Correct Carnivorous Tree
How to slow yourself down (for playing nice with others)
As programers say: Strive to be lazy
Is it a bad idea to replace pull-up resistors with hard pull-ups?
How can dragons propel their breath attacks to a long distance
What does "Ich wusste, dass aus dir mal was wird" mean?
What happens if a creature that would fight isn't on the battlefield anymore?
A cryptic tricolour
Parse Math Expression
How would I manually (no third-party libraries) evaluate an equation from a string in C#?Double.TryParse doesn't allow to use divisions (fractions) as inputC# - Load Mathematical FormulaConvert string into mathematical expressionFunction of count / process a series of combination numbers and math operations ('+', '-', '*", '/')Equation (expression) parser with precedence?Is there a string math evaluator in .NET?operators as stringsBest Free C# Math Parser using variables, user defined functions, custom operatorsDoing math in vb.net like Eval in javascriptBest way to parse command line arguments in C#?Replacing .NET WebBrowser control with a better browser, like Chrome?Parse JSON in C#Reflecting parameter name: abuse of C# lambda expressions or Syntax brilliance?Boolean and Math Expression ParserSimple state machine example in C#?Curious null-coalescing operator custom implicit conversion behaviourWhy is processing a sorted array slower than an unsorted array?Why not inherit from List<T>?Found conflicts between different versions of the same dependent assembly that could not be resolved
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
Is there an easy way to parse a simple math expression represented as a string such as (x+(2*x)/(1-x)), provide a value for x, and get a result?
I looked at the VSAEngine per several online examples, however, I am getting a warning that this assembly has been deprecated and not to use it.
If it makes any differences, I am using .NET 4.0.
c# .net c#-4.0
add a comment |
Is there an easy way to parse a simple math expression represented as a string such as (x+(2*x)/(1-x)), provide a value for x, and get a result?
I looked at the VSAEngine per several online examples, however, I am getting a warning that this assembly has been deprecated and not to use it.
If it makes any differences, I am using .NET 4.0.
c# .net c#-4.0
I posted full source for this problem here: stackoverflow.com/questions/174664/operators-as-strings
– Austin Salonen
Oct 19 '10 at 22:08
possible duplicate of Is it possible to compile and execute new code at runtime in .NET?
– nawfal
May 31 '13 at 16:23
possible duplicate of Is there a string math evaluator in .NET?
– Robert MacLean
Oct 15 '14 at 13:13
add a comment |
Is there an easy way to parse a simple math expression represented as a string such as (x+(2*x)/(1-x)), provide a value for x, and get a result?
I looked at the VSAEngine per several online examples, however, I am getting a warning that this assembly has been deprecated and not to use it.
If it makes any differences, I am using .NET 4.0.
c# .net c#-4.0
Is there an easy way to parse a simple math expression represented as a string such as (x+(2*x)/(1-x)), provide a value for x, and get a result?
I looked at the VSAEngine per several online examples, however, I am getting a warning that this assembly has been deprecated and not to use it.
If it makes any differences, I am using .NET 4.0.
c# .net c#-4.0
c# .net c#-4.0
edited Apr 30 '13 at 15:26
Steve Konves
2,17732041
2,17732041
asked Oct 19 '10 at 21:19
BrandonBrandon
4,947135693
4,947135693
I posted full source for this problem here: stackoverflow.com/questions/174664/operators-as-strings
– Austin Salonen
Oct 19 '10 at 22:08
possible duplicate of Is it possible to compile and execute new code at runtime in .NET?
– nawfal
May 31 '13 at 16:23
possible duplicate of Is there a string math evaluator in .NET?
– Robert MacLean
Oct 15 '14 at 13:13
add a comment |
I posted full source for this problem here: stackoverflow.com/questions/174664/operators-as-strings
– Austin Salonen
Oct 19 '10 at 22:08
possible duplicate of Is it possible to compile and execute new code at runtime in .NET?
– nawfal
May 31 '13 at 16:23
possible duplicate of Is there a string math evaluator in .NET?
– Robert MacLean
Oct 15 '14 at 13:13
I posted full source for this problem here: stackoverflow.com/questions/174664/operators-as-strings
– Austin Salonen
Oct 19 '10 at 22:08
I posted full source for this problem here: stackoverflow.com/questions/174664/operators-as-strings
– Austin Salonen
Oct 19 '10 at 22:08
possible duplicate of Is it possible to compile and execute new code at runtime in .NET?
– nawfal
May 31 '13 at 16:23
possible duplicate of Is it possible to compile and execute new code at runtime in .NET?
– nawfal
May 31 '13 at 16:23
possible duplicate of Is there a string math evaluator in .NET?
– Robert MacLean
Oct 15 '14 at 13:13
possible duplicate of Is there a string math evaluator in .NET?
– Robert MacLean
Oct 15 '14 at 13:13
add a comment |
9 Answers
9
active
oldest
votes
You can try using DataTable.Compute.
A related one is DataColumn.Expression.
Also check out: Doing math in vb.net like Eval in javascript
Note: I haven't used these myself.
Since I was not doing any trig calculations (just simple math), the DataTable.Compute option was the easiest to implement.
– Brandon
Oct 20 '10 at 16:44
add a comment |
I urge caution against choosing an existing generic expression evaluator over a purpose-built math evaluator. The reason for this is that the expression evaluators are not limited to just math. A clever individual could use this to create an instance of any type in the framework and call any method on the type, and that would allow him to do some decidedly unwelcome things. For example: new System.Net.WebClient().DownloadFile("illegalchildpornurl", "C:openme.gif")
will evaluate just fine in most of those, and do just what it sounds like it would (and make you a felon at the same time).
This doesn't mean don't look for something that's already written. It just means be careful. You want one that does math, and only math. Most of what's already out there isn't that picky.
add a comment |
I was recently using mXparser, which is a math parser library. It gives you a lot of flexibility, such as variables, functions, constants, operators. You will find below a few usage examples:
Example 1 - simple formula
Expression e = new Expression("1 + pi");
double v = e.calculate();
Example 2 - formula with variables, functions, etc.
Argument x = new Argument("x = 2");
Constant a = new Constant("a = sin(10)");
Function f = new Function("f(t) = t^2");
Expression e = new Expression("2*x + a - f(10)", x, a, f);
double v = e.calculate();
https://mxparser.codeplex.com/
http://mathparser.org/
Found recntly - you can try the syntax (and see the use case) via the Scalar Calculator app that is powered by mXparser.
Best regards
Best regards
add a comment |
I would also have a look at Jace (https://github.com/pieterderycke/Jace). Jace is a high performance math parser and calculation engine that supports all the .NET flavors (.NET 4.x, Windows Phone, Windows Store, ...). Jace is also available through NuGet: https://www.nuget.org/packages/Jace
add a comment |
Here is one way to do it. This code is written in Java. Note it does not handle negative numbers right now, but you can add that.
public class ExpressionParser
public double eval(String exp, Map<String, Double> vars)
int bracketCounter = 0;
int operatorIndex = -1;
for(int i=0; i<exp.length(); i++)
if(operatorIndex < 0)
exp = exp.trim();
if(exp.charAt(0) == '(' && exp.charAt(exp.length()-1) == ')')
return eval(exp.substring(1, exp.length()-1), vars);
else if(vars.containsKey(exp))
return vars.get(exp);
else
return Double.parseDouble(exp);
else
switch(exp.charAt(operatorIndex))
case '+':
return eval(exp.substring(0, operatorIndex), vars) + eval(exp.substring(operatorIndex+1), vars);
case '-':
return eval(exp.substring(0, operatorIndex), vars) - eval(exp.substring(operatorIndex+1), vars);
case '*':
return eval(exp.substring(0, operatorIndex), vars) * eval(exp.substring(operatorIndex+1), vars);
case '/':
return eval(exp.substring(0, operatorIndex), vars) / eval(exp.substring(operatorIndex+1), vars);
return 0;
You need to import java.util.Map.
Here is how I use this code:
ExpressionParser p = new ExpressionParser();
Map vars = new HashMap<String, Double>();
vars.put("x", 2.50);
System.out.println(p.eval(" 5 + 6 * x - 1", vars));
1
This is a beautiful piece of code. Thank you
– Illishar
Mar 16 '18 at 8:44
Thank you @Illishar
– user4617883
Mar 16 '18 at 16:01
add a comment |
Another option you may want to look into is the Spring.NET Framework's expression evaluation functionality. It can do a lot more than math, too.
However, the entire Spring.NET Framework might be a bit of overkill for your needs if you don't require the rest of the functionality.
add a comment |
Related: Equation expression parser with precedence.
add a comment |
As I answered in this thread (Best Free C# Math Parser using variables, user defined functions, custom operators), you can use Mathos Parser, which you can simply paste into your source code.
Mathos.Parser.MathParser parser = new Mathos.Parser.MathParser();
string expr = "(x+(2*x)/(1-x))"; // the expression
decimal result = 0; // the storage of the result
parser.LocalVariables.Add("x", 41); // 41 is the value of x
result = parser.Parse(expr); // parsing
Console.WriteLine(result); // 38.95
Unfortunately this project is hosted at Codeplex, which is closing. I can't manage to even get a look at the source at Codeplex right now. It would be nice if the project could be rehosted on Github or Bitbucket or the like.
– Nic Foster
Jun 12 '17 at 5:07
@NicFoster, please take a look at github.com/MathosProject/Mathos-Parser. There are also other versions of it at github.com/MathosProject.
– Artem
Jun 12 '17 at 7:39
add a comment |
I recomend you to use MEEL for this.
// parse string to IExpression (symbolic type)
IExpression expression = BaseExpression.Parse("(x+(2*x)/(1-x))");
// create your own collection for attributes
var attributes = new MathAttributeCollection();
// create local variable named "x" with value 5
var attributeX = new ScalarAttrInt("x") Value = new ScalarConstInt(5);
attributes.Add(attributeX);
// execute math expression where x=5
var result = expression.Execute(attributes);
MessageBox.Show(result.GetText());
// result: 2.5
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3972854%2fparse-math-expression%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
9 Answers
9
active
oldest
votes
9 Answers
9
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can try using DataTable.Compute.
A related one is DataColumn.Expression.
Also check out: Doing math in vb.net like Eval in javascript
Note: I haven't used these myself.
Since I was not doing any trig calculations (just simple math), the DataTable.Compute option was the easiest to implement.
– Brandon
Oct 20 '10 at 16:44
add a comment |
You can try using DataTable.Compute.
A related one is DataColumn.Expression.
Also check out: Doing math in vb.net like Eval in javascript
Note: I haven't used these myself.
Since I was not doing any trig calculations (just simple math), the DataTable.Compute option was the easiest to implement.
– Brandon
Oct 20 '10 at 16:44
add a comment |
You can try using DataTable.Compute.
A related one is DataColumn.Expression.
Also check out: Doing math in vb.net like Eval in javascript
Note: I haven't used these myself.
You can try using DataTable.Compute.
A related one is DataColumn.Expression.
Also check out: Doing math in vb.net like Eval in javascript
Note: I haven't used these myself.
edited May 23 '17 at 11:47
Community♦
11
11
answered Oct 19 '10 at 21:28
Aryabhatta
Since I was not doing any trig calculations (just simple math), the DataTable.Compute option was the easiest to implement.
– Brandon
Oct 20 '10 at 16:44
add a comment |
Since I was not doing any trig calculations (just simple math), the DataTable.Compute option was the easiest to implement.
– Brandon
Oct 20 '10 at 16:44
Since I was not doing any trig calculations (just simple math), the DataTable.Compute option was the easiest to implement.
– Brandon
Oct 20 '10 at 16:44
Since I was not doing any trig calculations (just simple math), the DataTable.Compute option was the easiest to implement.
– Brandon
Oct 20 '10 at 16:44
add a comment |
I urge caution against choosing an existing generic expression evaluator over a purpose-built math evaluator. The reason for this is that the expression evaluators are not limited to just math. A clever individual could use this to create an instance of any type in the framework and call any method on the type, and that would allow him to do some decidedly unwelcome things. For example: new System.Net.WebClient().DownloadFile("illegalchildpornurl", "C:openme.gif")
will evaluate just fine in most of those, and do just what it sounds like it would (and make you a felon at the same time).
This doesn't mean don't look for something that's already written. It just means be careful. You want one that does math, and only math. Most of what's already out there isn't that picky.
add a comment |
I urge caution against choosing an existing generic expression evaluator over a purpose-built math evaluator. The reason for this is that the expression evaluators are not limited to just math. A clever individual could use this to create an instance of any type in the framework and call any method on the type, and that would allow him to do some decidedly unwelcome things. For example: new System.Net.WebClient().DownloadFile("illegalchildpornurl", "C:openme.gif")
will evaluate just fine in most of those, and do just what it sounds like it would (and make you a felon at the same time).
This doesn't mean don't look for something that's already written. It just means be careful. You want one that does math, and only math. Most of what's already out there isn't that picky.
add a comment |
I urge caution against choosing an existing generic expression evaluator over a purpose-built math evaluator. The reason for this is that the expression evaluators are not limited to just math. A clever individual could use this to create an instance of any type in the framework and call any method on the type, and that would allow him to do some decidedly unwelcome things. For example: new System.Net.WebClient().DownloadFile("illegalchildpornurl", "C:openme.gif")
will evaluate just fine in most of those, and do just what it sounds like it would (and make you a felon at the same time).
This doesn't mean don't look for something that's already written. It just means be careful. You want one that does math, and only math. Most of what's already out there isn't that picky.
I urge caution against choosing an existing generic expression evaluator over a purpose-built math evaluator. The reason for this is that the expression evaluators are not limited to just math. A clever individual could use this to create an instance of any type in the framework and call any method on the type, and that would allow him to do some decidedly unwelcome things. For example: new System.Net.WebClient().DownloadFile("illegalchildpornurl", "C:openme.gif")
will evaluate just fine in most of those, and do just what it sounds like it would (and make you a felon at the same time).
This doesn't mean don't look for something that's already written. It just means be careful. You want one that does math, and only math. Most of what's already out there isn't that picky.
edited Sep 20 '11 at 19:16
answered Oct 19 '10 at 21:39
Joel CoehoornJoel Coehoorn
314k97498737
314k97498737
add a comment |
add a comment |
I was recently using mXparser, which is a math parser library. It gives you a lot of flexibility, such as variables, functions, constants, operators. You will find below a few usage examples:
Example 1 - simple formula
Expression e = new Expression("1 + pi");
double v = e.calculate();
Example 2 - formula with variables, functions, etc.
Argument x = new Argument("x = 2");
Constant a = new Constant("a = sin(10)");
Function f = new Function("f(t) = t^2");
Expression e = new Expression("2*x + a - f(10)", x, a, f);
double v = e.calculate();
https://mxparser.codeplex.com/
http://mathparser.org/
Found recntly - you can try the syntax (and see the use case) via the Scalar Calculator app that is powered by mXparser.
Best regards
Best regards
add a comment |
I was recently using mXparser, which is a math parser library. It gives you a lot of flexibility, such as variables, functions, constants, operators. You will find below a few usage examples:
Example 1 - simple formula
Expression e = new Expression("1 + pi");
double v = e.calculate();
Example 2 - formula with variables, functions, etc.
Argument x = new Argument("x = 2");
Constant a = new Constant("a = sin(10)");
Function f = new Function("f(t) = t^2");
Expression e = new Expression("2*x + a - f(10)", x, a, f);
double v = e.calculate();
https://mxparser.codeplex.com/
http://mathparser.org/
Found recntly - you can try the syntax (and see the use case) via the Scalar Calculator app that is powered by mXparser.
Best regards
Best regards
add a comment |
I was recently using mXparser, which is a math parser library. It gives you a lot of flexibility, such as variables, functions, constants, operators. You will find below a few usage examples:
Example 1 - simple formula
Expression e = new Expression("1 + pi");
double v = e.calculate();
Example 2 - formula with variables, functions, etc.
Argument x = new Argument("x = 2");
Constant a = new Constant("a = sin(10)");
Function f = new Function("f(t) = t^2");
Expression e = new Expression("2*x + a - f(10)", x, a, f);
double v = e.calculate();
https://mxparser.codeplex.com/
http://mathparser.org/
Found recntly - you can try the syntax (and see the use case) via the Scalar Calculator app that is powered by mXparser.
Best regards
Best regards
I was recently using mXparser, which is a math parser library. It gives you a lot of flexibility, such as variables, functions, constants, operators. You will find below a few usage examples:
Example 1 - simple formula
Expression e = new Expression("1 + pi");
double v = e.calculate();
Example 2 - formula with variables, functions, etc.
Argument x = new Argument("x = 2");
Constant a = new Constant("a = sin(10)");
Function f = new Function("f(t) = t^2");
Expression e = new Expression("2*x + a - f(10)", x, a, f);
double v = e.calculate();
https://mxparser.codeplex.com/
http://mathparser.org/
Found recntly - you can try the syntax (and see the use case) via the Scalar Calculator app that is powered by mXparser.
Best regards
Best regards
edited Mar 23 at 11:55
answered Mar 4 '16 at 21:47
Leroy KeganLeroy Kegan
57655
57655
add a comment |
add a comment |
I would also have a look at Jace (https://github.com/pieterderycke/Jace). Jace is a high performance math parser and calculation engine that supports all the .NET flavors (.NET 4.x, Windows Phone, Windows Store, ...). Jace is also available through NuGet: https://www.nuget.org/packages/Jace
add a comment |
I would also have a look at Jace (https://github.com/pieterderycke/Jace). Jace is a high performance math parser and calculation engine that supports all the .NET flavors (.NET 4.x, Windows Phone, Windows Store, ...). Jace is also available through NuGet: https://www.nuget.org/packages/Jace
add a comment |
I would also have a look at Jace (https://github.com/pieterderycke/Jace). Jace is a high performance math parser and calculation engine that supports all the .NET flavors (.NET 4.x, Windows Phone, Windows Store, ...). Jace is also available through NuGet: https://www.nuget.org/packages/Jace
I would also have a look at Jace (https://github.com/pieterderycke/Jace). Jace is a high performance math parser and calculation engine that supports all the .NET flavors (.NET 4.x, Windows Phone, Windows Store, ...). Jace is also available through NuGet: https://www.nuget.org/packages/Jace
answered Jan 27 '14 at 8:19
MuSTaNGMuSTaNG
3,2372106
3,2372106
add a comment |
add a comment |
Here is one way to do it. This code is written in Java. Note it does not handle negative numbers right now, but you can add that.
public class ExpressionParser
public double eval(String exp, Map<String, Double> vars)
int bracketCounter = 0;
int operatorIndex = -1;
for(int i=0; i<exp.length(); i++)
if(operatorIndex < 0)
exp = exp.trim();
if(exp.charAt(0) == '(' && exp.charAt(exp.length()-1) == ')')
return eval(exp.substring(1, exp.length()-1), vars);
else if(vars.containsKey(exp))
return vars.get(exp);
else
return Double.parseDouble(exp);
else
switch(exp.charAt(operatorIndex))
case '+':
return eval(exp.substring(0, operatorIndex), vars) + eval(exp.substring(operatorIndex+1), vars);
case '-':
return eval(exp.substring(0, operatorIndex), vars) - eval(exp.substring(operatorIndex+1), vars);
case '*':
return eval(exp.substring(0, operatorIndex), vars) * eval(exp.substring(operatorIndex+1), vars);
case '/':
return eval(exp.substring(0, operatorIndex), vars) / eval(exp.substring(operatorIndex+1), vars);
return 0;
You need to import java.util.Map.
Here is how I use this code:
ExpressionParser p = new ExpressionParser();
Map vars = new HashMap<String, Double>();
vars.put("x", 2.50);
System.out.println(p.eval(" 5 + 6 * x - 1", vars));
1
This is a beautiful piece of code. Thank you
– Illishar
Mar 16 '18 at 8:44
Thank you @Illishar
– user4617883
Mar 16 '18 at 16:01
add a comment |
Here is one way to do it. This code is written in Java. Note it does not handle negative numbers right now, but you can add that.
public class ExpressionParser
public double eval(String exp, Map<String, Double> vars)
int bracketCounter = 0;
int operatorIndex = -1;
for(int i=0; i<exp.length(); i++)
if(operatorIndex < 0)
exp = exp.trim();
if(exp.charAt(0) == '(' && exp.charAt(exp.length()-1) == ')')
return eval(exp.substring(1, exp.length()-1), vars);
else if(vars.containsKey(exp))
return vars.get(exp);
else
return Double.parseDouble(exp);
else
switch(exp.charAt(operatorIndex))
case '+':
return eval(exp.substring(0, operatorIndex), vars) + eval(exp.substring(operatorIndex+1), vars);
case '-':
return eval(exp.substring(0, operatorIndex), vars) - eval(exp.substring(operatorIndex+1), vars);
case '*':
return eval(exp.substring(0, operatorIndex), vars) * eval(exp.substring(operatorIndex+1), vars);
case '/':
return eval(exp.substring(0, operatorIndex), vars) / eval(exp.substring(operatorIndex+1), vars);
return 0;
You need to import java.util.Map.
Here is how I use this code:
ExpressionParser p = new ExpressionParser();
Map vars = new HashMap<String, Double>();
vars.put("x", 2.50);
System.out.println(p.eval(" 5 + 6 * x - 1", vars));
1
This is a beautiful piece of code. Thank you
– Illishar
Mar 16 '18 at 8:44
Thank you @Illishar
– user4617883
Mar 16 '18 at 16:01
add a comment |
Here is one way to do it. This code is written in Java. Note it does not handle negative numbers right now, but you can add that.
public class ExpressionParser
public double eval(String exp, Map<String, Double> vars)
int bracketCounter = 0;
int operatorIndex = -1;
for(int i=0; i<exp.length(); i++)
if(operatorIndex < 0)
exp = exp.trim();
if(exp.charAt(0) == '(' && exp.charAt(exp.length()-1) == ')')
return eval(exp.substring(1, exp.length()-1), vars);
else if(vars.containsKey(exp))
return vars.get(exp);
else
return Double.parseDouble(exp);
else
switch(exp.charAt(operatorIndex))
case '+':
return eval(exp.substring(0, operatorIndex), vars) + eval(exp.substring(operatorIndex+1), vars);
case '-':
return eval(exp.substring(0, operatorIndex), vars) - eval(exp.substring(operatorIndex+1), vars);
case '*':
return eval(exp.substring(0, operatorIndex), vars) * eval(exp.substring(operatorIndex+1), vars);
case '/':
return eval(exp.substring(0, operatorIndex), vars) / eval(exp.substring(operatorIndex+1), vars);
return 0;
You need to import java.util.Map.
Here is how I use this code:
ExpressionParser p = new ExpressionParser();
Map vars = new HashMap<String, Double>();
vars.put("x", 2.50);
System.out.println(p.eval(" 5 + 6 * x - 1", vars));
Here is one way to do it. This code is written in Java. Note it does not handle negative numbers right now, but you can add that.
public class ExpressionParser
public double eval(String exp, Map<String, Double> vars)
int bracketCounter = 0;
int operatorIndex = -1;
for(int i=0; i<exp.length(); i++)
if(operatorIndex < 0)
exp = exp.trim();
if(exp.charAt(0) == '(' && exp.charAt(exp.length()-1) == ')')
return eval(exp.substring(1, exp.length()-1), vars);
else if(vars.containsKey(exp))
return vars.get(exp);
else
return Double.parseDouble(exp);
else
switch(exp.charAt(operatorIndex))
case '+':
return eval(exp.substring(0, operatorIndex), vars) + eval(exp.substring(operatorIndex+1), vars);
case '-':
return eval(exp.substring(0, operatorIndex), vars) - eval(exp.substring(operatorIndex+1), vars);
case '*':
return eval(exp.substring(0, operatorIndex), vars) * eval(exp.substring(operatorIndex+1), vars);
case '/':
return eval(exp.substring(0, operatorIndex), vars) / eval(exp.substring(operatorIndex+1), vars);
return 0;
You need to import java.util.Map.
Here is how I use this code:
ExpressionParser p = new ExpressionParser();
Map vars = new HashMap<String, Double>();
vars.put("x", 2.50);
System.out.println(p.eval(" 5 + 6 * x - 1", vars));
answered Oct 15 '17 at 5:02
user4617883user4617883
374312
374312
1
This is a beautiful piece of code. Thank you
– Illishar
Mar 16 '18 at 8:44
Thank you @Illishar
– user4617883
Mar 16 '18 at 16:01
add a comment |
1
This is a beautiful piece of code. Thank you
– Illishar
Mar 16 '18 at 8:44
Thank you @Illishar
– user4617883
Mar 16 '18 at 16:01
1
1
This is a beautiful piece of code. Thank you
– Illishar
Mar 16 '18 at 8:44
This is a beautiful piece of code. Thank you
– Illishar
Mar 16 '18 at 8:44
Thank you @Illishar
– user4617883
Mar 16 '18 at 16:01
Thank you @Illishar
– user4617883
Mar 16 '18 at 16:01
add a comment |
Another option you may want to look into is the Spring.NET Framework's expression evaluation functionality. It can do a lot more than math, too.
However, the entire Spring.NET Framework might be a bit of overkill for your needs if you don't require the rest of the functionality.
add a comment |
Another option you may want to look into is the Spring.NET Framework's expression evaluation functionality. It can do a lot more than math, too.
However, the entire Spring.NET Framework might be a bit of overkill for your needs if you don't require the rest of the functionality.
add a comment |
Another option you may want to look into is the Spring.NET Framework's expression evaluation functionality. It can do a lot more than math, too.
However, the entire Spring.NET Framework might be a bit of overkill for your needs if you don't require the rest of the functionality.
Another option you may want to look into is the Spring.NET Framework's expression evaluation functionality. It can do a lot more than math, too.
However, the entire Spring.NET Framework might be a bit of overkill for your needs if you don't require the rest of the functionality.
answered Oct 19 '10 at 21:31
Joshua RodgersJoshua Rodgers
4,57722529
4,57722529
add a comment |
add a comment |
Related: Equation expression parser with precedence.
add a comment |
Related: Equation expression parser with precedence.
add a comment |
Related: Equation expression parser with precedence.
Related: Equation expression parser with precedence.
edited May 23 '17 at 12:18
Community♦
11
11
answered Oct 19 '10 at 21:34
Jared UpdikeJared Updike
5,17853862
5,17853862
add a comment |
add a comment |
As I answered in this thread (Best Free C# Math Parser using variables, user defined functions, custom operators), you can use Mathos Parser, which you can simply paste into your source code.
Mathos.Parser.MathParser parser = new Mathos.Parser.MathParser();
string expr = "(x+(2*x)/(1-x))"; // the expression
decimal result = 0; // the storage of the result
parser.LocalVariables.Add("x", 41); // 41 is the value of x
result = parser.Parse(expr); // parsing
Console.WriteLine(result); // 38.95
Unfortunately this project is hosted at Codeplex, which is closing. I can't manage to even get a look at the source at Codeplex right now. It would be nice if the project could be rehosted on Github or Bitbucket or the like.
– Nic Foster
Jun 12 '17 at 5:07
@NicFoster, please take a look at github.com/MathosProject/Mathos-Parser. There are also other versions of it at github.com/MathosProject.
– Artem
Jun 12 '17 at 7:39
add a comment |
As I answered in this thread (Best Free C# Math Parser using variables, user defined functions, custom operators), you can use Mathos Parser, which you can simply paste into your source code.
Mathos.Parser.MathParser parser = new Mathos.Parser.MathParser();
string expr = "(x+(2*x)/(1-x))"; // the expression
decimal result = 0; // the storage of the result
parser.LocalVariables.Add("x", 41); // 41 is the value of x
result = parser.Parse(expr); // parsing
Console.WriteLine(result); // 38.95
Unfortunately this project is hosted at Codeplex, which is closing. I can't manage to even get a look at the source at Codeplex right now. It would be nice if the project could be rehosted on Github or Bitbucket or the like.
– Nic Foster
Jun 12 '17 at 5:07
@NicFoster, please take a look at github.com/MathosProject/Mathos-Parser. There are also other versions of it at github.com/MathosProject.
– Artem
Jun 12 '17 at 7:39
add a comment |
As I answered in this thread (Best Free C# Math Parser using variables, user defined functions, custom operators), you can use Mathos Parser, which you can simply paste into your source code.
Mathos.Parser.MathParser parser = new Mathos.Parser.MathParser();
string expr = "(x+(2*x)/(1-x))"; // the expression
decimal result = 0; // the storage of the result
parser.LocalVariables.Add("x", 41); // 41 is the value of x
result = parser.Parse(expr); // parsing
Console.WriteLine(result); // 38.95
As I answered in this thread (Best Free C# Math Parser using variables, user defined functions, custom operators), you can use Mathos Parser, which you can simply paste into your source code.
Mathos.Parser.MathParser parser = new Mathos.Parser.MathParser();
string expr = "(x+(2*x)/(1-x))"; // the expression
decimal result = 0; // the storage of the result
parser.LocalVariables.Add("x", 41); // 41 is the value of x
result = parser.Parse(expr); // parsing
Console.WriteLine(result); // 38.95
edited May 23 '17 at 12:18
Community♦
11
11
answered Apr 30 '13 at 14:58
ArtemArtem
494921
494921
Unfortunately this project is hosted at Codeplex, which is closing. I can't manage to even get a look at the source at Codeplex right now. It would be nice if the project could be rehosted on Github or Bitbucket or the like.
– Nic Foster
Jun 12 '17 at 5:07
@NicFoster, please take a look at github.com/MathosProject/Mathos-Parser. There are also other versions of it at github.com/MathosProject.
– Artem
Jun 12 '17 at 7:39
add a comment |
Unfortunately this project is hosted at Codeplex, which is closing. I can't manage to even get a look at the source at Codeplex right now. It would be nice if the project could be rehosted on Github or Bitbucket or the like.
– Nic Foster
Jun 12 '17 at 5:07
@NicFoster, please take a look at github.com/MathosProject/Mathos-Parser. There are also other versions of it at github.com/MathosProject.
– Artem
Jun 12 '17 at 7:39
Unfortunately this project is hosted at Codeplex, which is closing. I can't manage to even get a look at the source at Codeplex right now. It would be nice if the project could be rehosted on Github or Bitbucket or the like.
– Nic Foster
Jun 12 '17 at 5:07
Unfortunately this project is hosted at Codeplex, which is closing. I can't manage to even get a look at the source at Codeplex right now. It would be nice if the project could be rehosted on Github or Bitbucket or the like.
– Nic Foster
Jun 12 '17 at 5:07
@NicFoster, please take a look at github.com/MathosProject/Mathos-Parser. There are also other versions of it at github.com/MathosProject.
– Artem
Jun 12 '17 at 7:39
@NicFoster, please take a look at github.com/MathosProject/Mathos-Parser. There are also other versions of it at github.com/MathosProject.
– Artem
Jun 12 '17 at 7:39
add a comment |
I recomend you to use MEEL for this.
// parse string to IExpression (symbolic type)
IExpression expression = BaseExpression.Parse("(x+(2*x)/(1-x))");
// create your own collection for attributes
var attributes = new MathAttributeCollection();
// create local variable named "x" with value 5
var attributeX = new ScalarAttrInt("x") Value = new ScalarConstInt(5);
attributes.Add(attributeX);
// execute math expression where x=5
var result = expression.Execute(attributes);
MessageBox.Show(result.GetText());
// result: 2.5
add a comment |
I recomend you to use MEEL for this.
// parse string to IExpression (symbolic type)
IExpression expression = BaseExpression.Parse("(x+(2*x)/(1-x))");
// create your own collection for attributes
var attributes = new MathAttributeCollection();
// create local variable named "x" with value 5
var attributeX = new ScalarAttrInt("x") Value = new ScalarConstInt(5);
attributes.Add(attributeX);
// execute math expression where x=5
var result = expression.Execute(attributes);
MessageBox.Show(result.GetText());
// result: 2.5
add a comment |
I recomend you to use MEEL for this.
// parse string to IExpression (symbolic type)
IExpression expression = BaseExpression.Parse("(x+(2*x)/(1-x))");
// create your own collection for attributes
var attributes = new MathAttributeCollection();
// create local variable named "x" with value 5
var attributeX = new ScalarAttrInt("x") Value = new ScalarConstInt(5);
attributes.Add(attributeX);
// execute math expression where x=5
var result = expression.Execute(attributes);
MessageBox.Show(result.GetText());
// result: 2.5
I recomend you to use MEEL for this.
// parse string to IExpression (symbolic type)
IExpression expression = BaseExpression.Parse("(x+(2*x)/(1-x))");
// create your own collection for attributes
var attributes = new MathAttributeCollection();
// create local variable named "x" with value 5
var attributeX = new ScalarAttrInt("x") Value = new ScalarConstInt(5);
attributes.Add(attributeX);
// execute math expression where x=5
var result = expression.Execute(attributes);
MessageBox.Show(result.GetText());
// result: 2.5
answered Feb 6 '15 at 10:26
supertohasupertoha
1377
1377
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3972854%2fparse-math-expression%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I posted full source for this problem here: stackoverflow.com/questions/174664/operators-as-strings
– Austin Salonen
Oct 19 '10 at 22:08
possible duplicate of Is it possible to compile and execute new code at runtime in .NET?
– nawfal
May 31 '13 at 16:23
possible duplicate of Is there a string math evaluator in .NET?
– Robert MacLean
Oct 15 '14 at 13:13