473,383 Members | 1,862 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Algebra in C#

I'm working on a project that deals with some algebra. Or, actually,
just math in general. It could eventually work it's way up to more
advanced math, analytics, etc.

Anyway, I'm looking for ideas on how to store the actual formulas
using classes.

For example:

class X
{
public Value;
}

class Y
{
public Value;
}

X x = new X();
X.Value = 10;

Y y = new Y();
Y.Value = 20;

Now, I want to store this formula:

x.Value + y.Value * 2

Which should give the value of 60.

Hope that makes sense. I thought about having a Formula class with a
List of classes and then build the formula when needed. Taking care
to add special classes like "multiply", etc but I don't think I like
that idea.

I also thought about storing a string somehow and then just parsing
the string and substitute keyword for classes.

Any suggestions?

Thanks
Jun 27 '08 #1
11 2181
On Fri, 25 Apr 2008 10:55:53 -0700, cbmeeks <cb*****@gmail.comwrote:
I'm working on a project that deals with some algebra. Or, actually,
just math in general. It could eventually work it's way up to more
advanced math, analytics, etc.

Anyway, I'm looking for ideas on how to store the actual formulas
using classes.
Well, it would take a very deep knowledge of exactly how this is going to
be used to provide any really good, specific advice.

However, a reasonably common approach would be to treat your expressions
as a tree graph of operators and operands. An operator instance would
have one or more operands as children. An operand could be a single
value, or the root of a sub-tree that represents a more complex
expression. Both operators and operands would share a base class used as
the fundamental element in the tree; that base class would be simply
something that returns a value.

Operator precedence and explicit precedence (i.e. parentheses) would
control the layout of the graph. The result of any given graph would be
obtained by recursively evaluating the operands for each operator until
you wind back up at the top having evaluated the root operator.

For added difficulty points, allow your values to take on more than one
actual numeric type, handling type conversion as necessary as you process
the graph. :)

That said, I would guess that there's already some solutions out there.
If you're looking for anything really elaborate, you might find it makes
more sense to search for and use a pre-existing package. I don't know for
sure that any exist, but it seems likely. Google would be helpful there,
obviously. :)

Pete
Jun 27 '08 #2
Thanks for replying.
Well, it would take a very deep knowledge of exactly how this is going to
be used to provide any really good, specific advice.

However, a reasonably common approach would be to treat your expressions
as a tree graph of operators and operands. An operator instance would
have one or more operands as children. An operand could be a single
value, or the root of a sub-tree that represents a more complex
expression. Both operators and operands would share a base class used as
the fundamental element in the tree; that base class would be simply
something that returns a value.
This sounds like the lines I was thinking of. I like the tree idea.
I will need to think of how to store a formula like:

M1 * 15 + (M2 / M3)

Where Mx = a class that returns a value.

I'm actually doing this in SQL and it works but it seems a little
kludgy. In SQL, I am storing each operator/operand as a row, then
assembling the row as a string and then parse the formula.

My long term goal is to allow a user to type the formula out in a text
box so I guess strings are still in my future.
Operator precedence and explicit precedence (i.e. parentheses) would
control the layout of the graph. The result of any given graph would be
obtained by recursively evaluating the operands for each operator until
you wind back up at the top having evaluated the root operator.
Right. This is what I am going to have to work on.
>
For added difficulty points, allow your values to take on more than one
actual numeric type, handling type conversion as necessary as you process
the graph. :)
That is interesting because I've only been working with doubles since
I thought that would allow more than enough precision for most
business related values. Is that wise?
>
That said, I would guess that there's already some solutions out there.
If you're looking for anything really elaborate, you might find it makes
more sense to search for and use a pre-existing package. I don't know for
sure that any exist, but it seems likely. Google would be helpful there,
obviously. :)

Pete

Yeah, but this is something I hope to offer as a service one day and I
enjoy the learning experience. :-)

Thanks Pete, you've been a lot of help.

-cecil
Jun 27 '08 #3
All mathematical "Formulas" in code eventually get reduced to math operations
on defined types and they return a result of a defined type (it could be a
complex number, matrix, doesn't matter). If you look at some of the
open-source math libraries, this is how they are structured. In other words,
you don't "store a formula", instead you have a method or methods with code
the *performs* the particular mathematical operation and returns it's result.
-- Peter
To be a success, arm yourself with the tools you need and learn how to use
them.

Site: http://www.eggheadcafe.com
http://petesbloggerama.blogspot.com
http://ittyurl.net
"cbmeeks" wrote:
I'm working on a project that deals with some algebra. Or, actually,
just math in general. It could eventually work it's way up to more
advanced math, analytics, etc.

Anyway, I'm looking for ideas on how to store the actual formulas
using classes.

For example:

class X
{
public Value;
}

class Y
{
public Value;
}

X x = new X();
X.Value = 10;

Y y = new Y();
Y.Value = 20;

Now, I want to store this formula:

x.Value + y.Value * 2

Which should give the value of 60.

Hope that makes sense. I thought about having a Formula class with a
List of classes and then build the formula when needed. Taking care
to add special classes like "multiply", etc but I don't think I like
that idea.

I also thought about storing a string somehow and then just parsing
the string and substitute keyword for classes.

Any suggestions?

Thanks
Jun 27 '08 #4
All mathematical "Formulas" in code eventually get reduced to math operations
on defined types and they return a result of a defined type (it could be a
complex number, matrix, doesn't matter). If you look at some of the
open-source math libraries, this is how they are structured. In other words,
you don't "store a formula", instead you have a method or methods with code
the *performs* the particular mathematical operation and returns it's result.
-- Peter

AH. That makes sense. Right now, I have some methods like that.

For example, I can do something like:

Metric m = new Metric();
m.Sum();
m.Avg();
m.PowSum();
m.MultiplySumBy(15);
etc...

That's working pretty well. So it's easy to do:

double r = m.Sum() + 15;

I will keep chugging along until I find a way to represent these chain
of actions :-)
Jun 27 '08 #5
I think you basicaly need a stack which pushes values and operators,
taking into account operator precedence.

I would find some open source compiler and see how they do it.

"cbmeeks" <cb*****@gmail.comwrote in message
news:94**********************************@b64g2000 hsa.googlegroups.com:
I'm working on a project that deals with some algebra. Or, actually,
just math in general. It could eventually work it's way up to more
advanced math, analytics, etc.

Anyway, I'm looking for ideas on how to store the actual formulas
using classes.

For example:

class X
{
public Value;
}

class Y
{
public Value;
}

X x = new X();
X.Value = 10;

Y y = new Y();
Y.Value = 20;

Now, I want to store this formula:

x.Value + y.Value * 2

Which should give the value of 60.

Hope that makes sense. I thought about having a Formula class with a
List of classes and then build the formula when needed. Taking care
to add special classes like "multiply", etc but I don't think I like
that idea.

I also thought about storing a string somehow and then just parsing
the string and substitute keyword for classes.

Any suggestions?

Thanks
Jun 27 '08 #6
On Fri, 25 Apr 2008 13:23:35 -0700, Ian Semmel <an****@rocketcomp.com.au>
wrote:
I think you basicaly need a stack which pushes values and operators,
taking into account operator precedence.

I would find some open source compiler and see how they do it.
For what it's worth, if you're going to follow this approach ("you" being
the OP, that is :) ), you might look at the FORTH language, and possibly
even try to find some source code for a FORTH interpreter.

One of the interesting things about FORTH is that it uses "reverse Polish
notation" for expressions. This is a little hard to read sometimes, but
it's actually very natural for a machine-based implementation that uses a
stack. If it's appropriate for your problem to represent your expressions
in RPN, a stack-based idea could work very well.

If not, then it gets a little tricky to convert a conventional
mathematical expression into a stack-based solution. Or looked at another
way, the tree representation I described earlier is actually a reasonably
natural way to use a stack (you wind up using recursion, which is
implicitly stack-based, to resolve the expression).

Pete
Jun 27 '08 #7
On Fri, 25 Apr 2008 11:53:57 -0700, cbmeeks <cb*****@gmail.comwrote:
This sounds like the lines I was thinking of. I like the tree idea.
I will need to think of how to store a formula like:

M1 * 15 + (M2 / M3)

Where Mx = a class that returns a value.
Sure. And each part is essentially an "Mx" also. That is, the class
representing the * operator is "a class that returns a value" and which
has two operands. Your tree is made up of these classes. Some will
simply be values, some will be operators that take one or more inputs.

The above formula would look like, in a tree, something like this (the
parentheses in that example are redundant, assuming normal operator
precedence):

PlusOp +---- MultiplyOp +---- M1
| |
| +---- 15
|
+---- DivideOp +---- M2
|
+---- M3

The + operator, having the lowest precedent and there being no parentheses
to override the precedence, is the root of the tree. It has as its
operands the two sub-expressions involving the * and / operators,
respectively.

The children of each node are operands. In two cases (the immediate
children of PlusOp), the operands are themselves operators with their own
children. At the leaf nodes of the tree, you have simple value instances.
I'm actually doing this in SQL and it works but it seems a little
kludgy. In SQL, I am storing each operator/operand as a row, then
assembling the row as a string and then parse the formula.

My long term goal is to allow a user to type the formula out in a text
box so I guess strings are still in my future.
The hardest part will be parsing the expression. However, that's a
relatively well-understood computer science problem. You should have
little trouble finding existing references on how to do it.
[...]
>For added difficulty points, allow your values to take on more than one
actual numeric type, handling type conversion as necessary as you
process
the graph. :)

That is interesting because I've only been working with doubles since
I thought that would allow more than enough precision for most
business related values. Is that wise?
Define "business related values". For many business applications, the
"decimal" type is actually more appropriate. Floating point ("double" or
"float") is susceptible to rounding errors. In financial applications,
this is often impermissible. The "decimal" type can suffer rounding
errors (try dividing one dollar into 3 equal parts :) ) as well depending
on how they are used, but the rules for dealing with rounding are usually
better-defined in that context.

That said, it may well be feasible to select a single numeric type,
whether "double" or "decimal", as your "lingua franca" for all of the
numeric expressions, rather than supporting mixed types.

Pete
Jun 27 '08 #8
On Fri, 25 Apr 2008 11:03:04 -0700, "Peter Duniho"
<Np*********@nnowslpianmk.comwrote:

[...]
>That said, I would guess that there's already some solutions out there.
If you're looking for anything really elaborate, you might find it makes
more sense to search for and use a pre-existing package. I don't know for
sure that any exist, but it seems likely. Google would be helpful there,
obviously. :)
Indeed - one of them confirms a hunch I had: that the solution to the
"representation" and "evaluation" parts of the problem (although not
the parsing) is already built into C# 3.0 in the form of expression
trees. Here's a very nice article that also provides the parsing, by
converting to a postfix representation (as you suggested) before
assembling the tree.

http://www.jot.fm/issues/issue_2008_...mn4/index.html

Regards,
Gilles.

Jun 27 '08 #9


"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local:
On Fri, 25 Apr 2008 13:23:35 -0700, Ian Semmel
<an****@rocketcomp.com.au>
wrote:

I think you basicaly need a stack which pushes values and operators,
taking into account operator precedence.

I would find some open source compiler and see how they do it.


For what it's worth, if you're going to follow this approach ("you"
being
the OP, that is :) ), you might look at the FORTH language, and possibly
even try to find some source code for a FORTH interpreter.

One of the interesting things about FORTH is that it uses "reverse
Polish
notation" for expressions. This is a little hard to read sometimes, but
it's actually very natural for a machine-based implementation that uses
a
stack. If it's appropriate for your problem to represent your
expressions
in RPN, a stack-based idea could work very well.

If not, then it gets a little tricky to convert a conventional
mathematical expression into a stack-based solution. Or looked at
another
way, the tree representation I described earlier is actually a
reasonably
natural way to use a stack (you wind up using recursion, which is
implicitly stack-based, to resolve the expression).

Pete
Possibly the easiest compiler to understand is the RATFOR compiler
invented by Kernighan and Plauger back in the 1970's which was described
in their book "Software Tools". It was a bit of a best-seller, and
basically led to "C" and Pascal (although both these were based on
algol).

Source code is available at :

http://sepwww.stanford.edu/software/ratfor.html

http://www.dgate.org/ratfor/

You have to know "C" to understand it, but it shows how everything is
parsed and tokenized.
Jun 27 '08 #10
Thanks for all of the suggestions guys!! I am going to look into the
RPN....that is very interesting!
Define "business related values". For many business applications, the
"decimal" type is actually more appropriate. Floating point ("double" or
"float") is susceptible to rounding errors. In financial applications,
this is often impermissible. The "decimal" type can suffer rounding
errors (try dividing one dollar into 3 equal parts :) ) as well depending
on how they are used, but the rules for dealing with rounding are usually
better-defined in that context.
AHH!!! Yeah, I had forgotten about that. hmmm...all of the Math
routines I use use double as input. Wouldn't
You guys have been great. Wish me luck!

Jun 27 '08 #11
Ian Semmel wrote:
Possibly the easiest compiler to understand is the RATFOR compiler
invented by Kernighan and Plauger back in the 1970's which was described
in their book "Software Tools". It was a bit of a best-seller, and
basically led to "C" and Pascal (although both these were based on algol).
I belive that Kernighan invented C before RATFOR. And that Wirth
created Pascal before both of them.

Arne
Jun 27 '08 #12

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

Similar topics

17
by: Rahul | last post by:
Hi. Well is there an open source computer algebra system written in python or at least having a python interface? I know of 2 efforts: pythonica and pyginac...are there any others? rahul
0
by: | last post by:
I need to write a relational algebra query for the following: Show the item_ID, item description and category description for all items where the supplier uses "rail" as the delivery_method. ...
0
by: Bernard Xhumga | last post by:
hello, I present my work : a freeware, (Language C, GnuPlot). Linear algebra : (fractions, 30 packages). http://www.geocities.com/xhungab/package.html The purpose of this work is to verify...
0
by: Wit Baas | last post by:
Hi all I need do the following based on Boolean Algebra ex 1. (M271/M272/M651)+(450/965)/M642/M646 All possible result M271 + 450 M271 + 965 M272 + 450 M272 + 965
3
by: Regardt | last post by:
Hi all I need do the following based on Boolean Algebra ex 1. (M271/M272/M651)+(450/965)/M642/M646 All possible result M271 + 450 M271 + 965 M272 + 450 M272 + 965
1
by: lava4112 | last post by:
Have a test on SQL, only teacher wants to know what type of relational algebra is a select, where, from--I have no idea and can not understand the teacher. We are using Concepts of Database...
3
Metallicat
by: Metallicat | last post by:
I have been posed and attempted to answer several questions but I do not seem to be getting anywhere. I have emailed my tutor a week ago and he has not responded, If anyone can take a look and help...
0
by: Bas | last post by:
On Sep 22, 10:02 am, Al Kabaila <akaba...@pcug.org.auwrote: That argument might have been valid 3 years ago, but as already said by others, Numeric and Numarray are deprecated. Numpy should be the...
2
by: Beany | last post by:
Hi, algebra: z = pr%q+w/x - y Perl code for this is: $z = $p * $r % $q + $w / $x - $y; Can someone please explain to me : in what order does Perl calculate the operators? What would be...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.