473,776 Members | 1,503 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2204
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******** *************** ***********@b64 g2000hsa.google groups.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****@rocketc omp.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*********@nn owslpianmk.comw rote:

[...]
>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*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local:
On Fri, 25 Apr 2008 13:23:35 -0700, Ian Semmel
<an****@rocketc omp.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

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

Similar topics

17
2549
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
2561
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. The relations (tables) and attributes are as follows: Item (item_ID, description, category, price, qty_on_hand) Category (code, description, tax_rate) Supplied_by (item_ID, supplier, date, delivery_method)
0
2161
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 with numeric applications, some properties of the linear algebra. addm, subm, multm, powm, smultm, transpose, det, minor, mminor, cofactor, mcofactor, adjoint, inverse, gauss, gaussjordan, LU,
0
998
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
4218
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
3670
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 Management by Pratt No I understand quieries, but not relational algebra Any Help would be great
3
2844
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 me out I would be grateful. Two of the questions are below, if anyone can help with these two I'm sure that I can crack the rest! Find the first name, surnames and address of the patients that have had at least one operation with broken bones. ...
0
2103
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 only thing needed for new users. I suggest you investigate a little bit more the next time you make such efforts, since this fact should be widely known among the users of the mentioned packages, see e.g. the huge warning at the numarray page:...
2
2466
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 calculated first, second, third etc... why? I just cant get my head around the algebra business.. How does perl simplify the above algebra?
0
9628
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
9464
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
10120
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
9923
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...
1
7471
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
5493
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4031
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3622
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2860
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.