473,729 Members | 2,144 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Math parser

Hello,

Does anyone know if there is a library or a sample project that can
parse strings with mathematical expressions inside ?

eg. string math = "(23 + 48) ^ 2 - (7.76 * 3.14)";
parser should calculate the result of this.

Atm I have my own parser, but it can only handle very simple
expressions with 2 operands eg. (34 * 89), I tried to expand the
functionality, but it's getting ugly (loads of substrings).

Any pointers ?

Thanks,

Janiek
Nov 17 '05 #1
12 12404
Hi,

You should be able to find something in the groups
This is a homework in almost all computer sciences careers :)

I did a search by "math parser" in google and found this:
http://www.c-sharpcorner.com/Code/20...hExpParser.asp

this is the link of the search
http://groups.google.com.my/groups?q...ublic.dotnet.*
cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Janiek Buysrogge" <J.*********@Te levic.com> wrote in message
news:2j******** *************** *********@4ax.c om...
Hello,

Does anyone know if there is a library or a sample project that can
parse strings with mathematical expressions inside ?

eg. string math = "(23 + 48) ^ 2 - (7.76 * 3.14)";
parser should calculate the result of this.

Atm I have my own parser, but it can only handle very simple
expressions with 2 operands eg. (34 * 89), I tried to expand the
functionality, but it's getting ugly (loads of substrings).

Any pointers ?

Thanks,

Janiek

Nov 17 '05 #2
Thank you, the links are very helpful.

Janiek

On Fri, 28 Oct 2005 09:25:50 -0400, "Ignacio Machin \( .NET/ C# MVP
\)" <ignacio.mach in AT dot.state.fl.us > wrote:
Hi,

You should be able to find something in the groups
This is a homework in almost all computer sciences careers :)

I did a search by "math parser" in google and found this:
http://www.c-sharpcorner.com/Code/20...hExpParser.asp

this is the link of the search
http://groups.google.com.my/groups?q...ublic.dotnet.*
cheers,


Nov 17 '05 #3
wouldn't it just be best to do the math then convert the answer to string?

double math = Math.Pow((23 + 48) , 2) - (7.76 * 3.14);
Console.WriteLi ne (Convert.ToStri ng(math));
"Janiek Buysrogge" wrote:
Hello,

Does anyone know if there is a library or a sample project that can
parse strings with mathematical expressions inside ?

eg. string math = "(23 + 48) ^ 2 - (7.76 * 3.14)";
parser should calculate the result of this.

Atm I have my own parser, but it can only handle very simple
expressions with 2 operands eg. (34 * 89), I tried to expand the
functionality, but it's getting ugly (loads of substrings).

Any pointers ?

Thanks,

Janiek

Nov 17 '05 #4
If you are willing to use C# version 2, you are free to use the source code
at:
http://www.frontiernet.net/~fredm/dps/Contents.htm . See chapter 3.

"Janiek Buysrogge" <J.*********@Te levic.com> wrote in message
news:2j******** *************** *********@4ax.c om...
Hello,

Does anyone know if there is a library or a sample project that can
parse strings with mathematical expressions inside ?

eg. string math = "(23 + 48) ^ 2 - (7.76 * 3.14)";
parser should calculate the result of this.

Atm I have my own parser, but it can only handle very simple
expressions with 2 operands eg. (34 * 89), I tried to expand the
functionality, but it's getting ugly (loads of substrings).

Any pointers ?

Thanks,

Janiek

Nov 17 '05 #5
Mike,

The expression will be formed at runtime as opposed to compile time.
That's why the OP is looking for an expression evaluator.

Brian

mike wrote:
wouldn't it just be best to do the math then convert the answer to string?

double math = Math.Pow((23 + 48) , 2) - (7.76 * 3.14);
Console.WriteLi ne (Convert.ToStri ng(math));
"Janiek Buysrogge" wrote:
Hello,

Does anyone know if there is a library or a sample project that can
parse strings with mathematical expressions inside ?

eg. string math = "(23 + 48) ^ 2 - (7.76 * 3.14)";
parser should calculate the result of this.

Atm I have my own parser, but it can only handle very simple
expressions with 2 operands eg. (34 * 89), I tried to expand the
functionality, but it's getting ugly (loads of substrings).

Any pointers ?

Thanks,

Janiek


Nov 17 '05 #6
Janiek,

I'm just throwing out some more options here.

1) You could use a compiler compiler. ANTLR is a popular one that
generates C# code. It would take some time to familiarize yourself
with EBNF grammars and how ANTLR works in general though.

<http://www.antlr.org>

2) Write your own parser. For an arithmetic expression evaluator it's
really not too difficult. There is a simple approach that inolves 3
basic steps. First, tokenize the expression. Second, convert the
infix notation to postfix notation. Finally, perform the evaluation
using postfix notation. There are other algorithms as well, but I
think infix to postfix is pretty easy to learn and it works well.

3) Download. Personally, I haven't seen any free ones written in C#
that I thought were worth downloading. The problem with the ones I've
seen is that they don't implement operator precedence and associativity
correctly, they don't accept user defined function, etc. It was an
issue for me, but it may not be an issue for you.

Brian

Janiek Buysrogge wrote:
Hello,

Does anyone know if there is a library or a sample project that can
parse strings with mathematical expressions inside ?

eg. string math = "(23 + 48) ^ 2 - (7.76 * 3.14)";
parser should calculate the result of this.

Atm I have my own parser, but it can only handle very simple
expressions with 2 operands eg. (34 * 89), I tried to expand the
functionality, but it's getting ugly (loads of substrings).

Any pointers ?

Thanks,

Janiek


Nov 17 '05 #7
Hello Janiek,

You can download csharp parser at http://cis.paisley.ac.uk/crow-ci0/CSTools47.zip.
And as an example they math expression parser.
You cant extended it also if you like.

Oleg
Hello,

Does anyone know if there is a library or a sample project that can
parse strings with mathematical expressions inside ?

eg. string math = "(23 + 48) ^ 2 - (7.76 * 3.14)"; parser should
calculate the result of this.

Atm I have my own parser, but it can only handle very simple
expressions with 2 operands eg. (34 * 89), I tried to expand the
functionality, but it's getting ugly (loads of substrings).

Any pointers ?

Thanks,

Janiek

Nov 17 '05 #8
If you don't mind dynamic code, you could do something like so:

string code = "Math.Pow(2 3 + 48, 2) - (7.76 * 3.14)";
string result = Eval.StringEval (code);
Console.WriteLi ne("Results: " + result);

Output
-------------------
Results: 5016.6336

Eval Class
--------------------
using System;
using System.Collecti ons.Generic;
using System.Reflecti on;
using System.Text;
using System.CodeDom;
using System.CodeDom. Compiler;

public static class Eval
{
private static string funcprefix = "using System;\r\n"
+ "public delegate void Proc();\r\n"
+ "public class Wrapper { \r\n"
+ " public static object Set(string name, object value) { \r\n"
+ " AppDomain.Curre ntDomain.SetDat a(name, value);\r\n"
+ " return value; \r\n"
+ " }\r\n"
+ " public static object Get(string name) { \r\n"
+ " return AppDomain.Curre ntDomain.GetDat a(name);\r\n"
+ " }\r\n"
+ " public static object Invoke(Proc proc) { \r\n"
+ " proc();\r\n"
+ " return null; \r\n"
+ " }\r\n"
+ " public static object Eval() { return \r\n";
static string funcsuffix = "; \r\n} }";
public static string StringEval(stri ng expr)
{
string program = funcprefix + expr + funcsuffix;
CompilerParamet ers cp = new CompilerParamet ers();
cp.GenerateExec utable = false;
cp.GenerateInMe mory = true;

CompilerResults results =
CodeDomProvider .CreateProvider ("C#").CompileA ssemblyFromSour ce(cp, new
string[]{program});
if ( results.Errors. HasErrors )
{
if ( results.Errors[0].ErrorNumber == "CS0029" )
return StringEval("Inv oke(delegate { " + expr + "; })");
throw new Exception(resul ts.Errors[0].ErrorText);
}
else
{
Assembly assm = results.Compile dAssembly;
Type target = assm.GetType("W rapper");
MethodInfo method = target.GetMetho d("Eval");
object result = method.Invoke(n ull, null);
return result == null ? null : result.ToString ();
}
}
}

--
William Stacey [MVP]

"Janiek Buysrogge" <J.*********@Te levic.com> wrote in message
news:2j******** *************** *********@4ax.c om...
Hello,

Does anyone know if there is a library or a sample project that can
parse strings with mathematical expressions inside ?

eg. string math = "(23 + 48) ^ 2 - (7.76 * 3.14)";
parser should calculate the result of this.

Atm I have my own parser, but it can only handle very simple
expressions with 2 operands eg. (34 * 89), I tried to expand the
functionality, but it's getting ugly (loads of substrings).

Any pointers ?

Thanks,

Janiek

Nov 17 '05 #9
Hello,

Thank you all for your contribution, I really appreciate it.

I will investigate further, the extendable parser seems the quickest
way, but the dynamic code also seems very interesting, it was a topic
of C# which I hadn't explored yet.

Again, thx for all the info,

Janiek
Nov 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
5285
by: Karalius, Joseph | last post by:
Can anyone explain what is happening here? I haven't found any useful info on Google yet. Thanks in advance. mmagnet:/home/jkaralius/src/zopeplone/Python-2.3.5 # make gcc -pthread -c -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DPy_BUILD_CORE -o Modules/python.o Modules/python.c gcc -pthread -c -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DPy_BUILD_CORE -o...
4
2112
by: romek chronowski | last post by:
Hi I'm looking for a code in c or c++ that chcecks math syntax e.g it should check that sin(x+2) is valid syntax but sin(x-+y) or sin((x) is invalid .Thanks in advance (it is very important to me)
3
1580
by: philippe mordellet | last post by:
hello everybody is it possible to ask the user to write a math function (ie : y = ax + b) in a textbox, and use this function to plot the curve in a window (how do Mathematica guys manage this, since its possible in their program ??? thanks for your kind help philippe mordellet -))
2
3519
by: Faraz | last post by:
Thanks Dave, To repeat the question: I am developing a WinForms application and I need a Math Expression validator, not an expression evaluator. So I want to be able to say... if ((sales - tax) > 20) THEN (x * y * 0.55) without knowing at runtime what the values of sales, tax, x and y are. Is there any software out there that will do this validation for me?
6
5571
by: PIEBALD | last post by:
Anyone got an infix to postfix (RPN) math notation converter? I've looked around a bit and haven't found anything quite what I want. I just want a method that will take a string in infix notation and return a string in Reverse Polish Notation.
11
1682
by: rob | last post by:
I have the following scenario. A user requests some math calculations from a server. The data and a library of basic formulas reside on the server. Now the user should be able to create more complex formulas based on the basic built in formulas as well as other complex formulas that the user created himself. These formulas will be either stored on the server or client and will be applied to the data on the server. Some of the formulas will...
0
2240
by: UncleRic | last post by:
Environment: Mac OS X (10.4.10) on MacBook Pro I'm a Perl Neophyte. I've downloaded the XML::Parser module and am attempting to install it in my working directory (referenced via PERL5LIB env): PERL5LIB=/Users/Ric/Library/Perl/ ls XML-Parser-2.34/ XML-Parser-2.34.tar
0
1294
by: Dancorbier | last post by:
uCalc Fast Math Parser 2.95 is now available. This component allows your applications to evaluate math expressions defined at runtime. The two major new enhancements in this version are faster speed, and more direct support for .NET. The previous version supported VB.NET with an include file, which didn't work directly with C#. Now there's a special .NET DLL file, which is designed to work with any .NET compiler. A full C# demo...
0
2204
by: jpecci | last post by:
I am approaching parsing for the first time and I can't find which solution is best for me. I need to process command line strings implementing mathematical operations (defined by me) on objects (defined by me), i.e. Prompt:> ((A*B)->C)+2 A,B,C could be matrixes or more complex objects *, -> ,+ could be operations which I want to implement Is there a parser approach most suitable for this?
0
8925
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8763
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9428
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9288
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9154
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8156
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4797
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2692
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.