Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to execute math expression? [duplicate]

Tags:

c#

Possible Duplicates:
Is there a string math evaluator in .NET?
Best and shortest way to evaluate mathematical expressions

I have a string variable

string exp = "12+34+4*56+(23*45+12)2/30"

what is the best way of doing it ? without the using of third party dll ?

like image 482
Jeevan Bhatt Avatar asked Nov 12 '10 09:11

Jeevan Bhatt


People also ask

How do you do expression in math?

How do you Write an Expression in Math? We write an expression in math by using numbers or variables and mathematical operators which are addition, subtraction, multiplication, and division. For example, the expression of the mathematical statement "4 added to 2", will be 2+4.

What are those two operation on mathematical expression?

The basic operations (addition and subtraction) are used in different forms such as multiplication (repeated addition) and division (repeated subtraction). Using these operations, the word problems are modeled into math expressions.

How do you find the mathematical expression in Python?

You can use the built-in Python eval() to dynamically evaluate expressions from a string-based or compiled-code-based input. If you pass in a string to eval() , then the function parses it, compiles it to bytecode, and evaluates it as a Python expression.


2 Answers

You need a mathematical expression parser. The best way in my opinion is not reinventing the wheel. An existing open source solution NCalc is a good choice.

like image 138
Hemant Avatar answered Nov 15 '22 23:11

Hemant


First translate it to an Expression Tree. If you use the built in Expression classes you get a compile method for free which gives you a compiled delegate, which thus is quite fast to evaluate. This is useful if you want to evaluate your expression for different parameters.

like image 30
CodesInChaos Avatar answered Nov 16 '22 00:11

CodesInChaos