Shunting-Yard on polynomial - c++

I'm currently working on a project that calculates polynomial expressions (We got this for a task at University). I'm storing a polynomial in a linked list and I've overloaded operators +,*,-,' for polynomials. The most difficult task that I've got is to parse an expression like this e.g. : (3x-(-x-1)^2)(x^3-2x^2+1)''where '' is second derivative. I've been googling a lot and couldn't find antyhing that could parse and make an postfix expression out of this when you have a variable x and numbers, is there a way to modify Shunting-Yard algorithm so that it could work on polynomials?
My node stores coefficient, power, pointer to the previous and next node and my Polynomial class supports every operation thats stated above. The only problem is how can I get a postfix expression out of a string that I put above? Btw. only '(' & ')' parentheses are supported, that makes it a bit easier.
For the example (3x-(-x-1)^2)(x^3-2x^2+1)'' I need to store the result of it in a polynomial that I made.
I can provide more if asked,
Thanks in advance!

Related

Regex for finding the index of Mathematical Operators

I am writing a program that takes a string of a mathematical expression, converts it to postfix notation. Which I have done, I am now trying to figure out how to evaluate this expression. I have left it in the data type of a queue, so my idea is to try and find the index of the first operator, then find the two numbers the come before it, send those to a new function which will evaluate them based on which operator is found (so one function for adding, one for subtracting ... etc). Im having trouble figuring out how to grab the index though.
Im trying to use the Queue method of indexOf and then passing it a regex for those operators. using \\W
y is a Queue. i've never used this type of character code before.
var z = y.indexOf("[\\W]")
i would like it to return the index of the first operator, in the case i currently have it is a "+"
currently that doesent find anything. i've also tried dropping those brackets an example Queue is
Queue(-1, 2, 3, *, +, 10, +)
Queue(1, 2, +)
which does mean i need a way to differ if its just a - or if its tied to the number. These are all Strings inside of the Queue
You have to
y.indexWhere(_.matches("\\W"))

Function to count an expression

Is there any function in C++ (included in some library or header file), that would count an expression from string?
Let's say we have a string, which equals 2 + 3 * 8 - 5 (but it's taken from user's keyboard, so we don't know what expression exactly it will be while writing the code), and we want this function co count it, but of course in the correct order (1. power / root 2. times / divide 3. increase / decrease).
I've tried to take all the numbers to an array of ints and operators to an array of chars (okay, actually vectors, because I don't know how many numbers and operators it's going to contain), but I'm not sure what to do next.
Note, that I'm asking if there's any function already written for that, if not I'm going to just try it again.
By count, I'm taking that to mean "evaluate the expression".
You'll have to use a parser generator like boost::spirit to do this properly. If you try hand-writing this I guarantee pain and misery for all involved.
Try looking on here for calculator apps, there are several:
http://boost-spirit.com/repository/applications/show_contents.php
There are also some simple calculator-style grammars in the boost::spirit examples.
Quite surprisingly, others before me have not redirected you to this particular algorithm which is easy to implement and converts your string into this special thing called Reverse Polish Notation (RPN). Computing expressions in RPN is easy, the hard part is implementing Shunting Yard but it is something done many times before and you may find many tutorials on the subject.
Quick overview of the algorithms:
PRN - RPN is a way to write expressions that eliminates the need for parentheses, thus it allows easier computation. Practically speaking, to compute one such expression you walk the string from left to right while keeping a stack of operands. Whenever you meet an operand, you push it onto the stack. Whenever you meet an operation token, you calculate its result on the last 2 operands (if the operation is binary ofcourse, on the last only if it is unary) and push it onto the stack. Rinse and repeat until the end of string.
Shunting Yard really is much harder to simply overview and if I do try to accomplish this task, this answer will end up looking much like the wikipedia article I linked above so I'll save that trouble to both of us.
Tl;DR; Go read the links in the first sentence.
You will have to do this yourself as there is no standard library that handles infix equation resolution
If you do, please include the code for what you are trying and we can help you

Writing INTEGRATOR similar to http://integrals.wolfram.com/index.jsp using parsing in java

Hi as part of my project I have been working on evaluation of arithmetic expression using reg-ex in java.
expressions are like this : 2+3/4(5+7)
first I will modify it to this : 2+3/4*(5+7)
and convert it to postfix
postfix: 23457+*/+
The procedure I have adopted is parsing all of the tokens (i.e. Integers,Operators,Open Paren,Close Paren) using Reg-Ex and then sorting by the i-th position of their occurrence. After that I converted that array of token into post-fix expression and then solved that expression, Until this point every thing is working fine.
Now I would like to extend it to solving differentiation,integration or solving quadratic equation.
foe ex: differentiate or integrate expression x^2+2*x+2
similar to http://integrals.wolfram.com/index.jsp
Is it possible? because right now I dont have any clue how to proceed with that?
Most calculators I am aware of - calculating equations/differentions and integrals using numerical analysis. This allows one to find a close solution to the exact (analytical one) solution, sometimes even for unsolveable equations (This is how we got the standard normal table, for the unsolveable normal density function)
For example, solving integrals - gaussian quardature is very common and efficeint way.
For solving equations - regula-falsi method is a simple and intuitive one
I think that most integral computation engines use the numerical approach just as amit said, however there's a way to compute it symbolically, but it's heuristic more than algorithmic, it's done by pattern matching. I think that Mathematica follows this approach.

Parse multi-stacks to find how to properly set up an equation

It has been awhile since I have used C++ I was wondering if anyone can give me a good way on how to create two stacks and then grab a user input such as: 1+6/3 and parse though this input to put the numbers in a 'number stack' and the operators in an 'operator stack', then make a priority list to make sure the proper operators are used in the equation first so the answer comes to 3. Any tips would be very much appreciated, I never use stacks.
http://en.wikipedia.org/wiki/Recursive_descent_parser
Evaluating arithmetic expressions from string in C++
What is the best way to evaluate mathematical expressions in C++?

Processing conditional statements

I'm not looking for an implementation, just pseudo-code, or at least an algorithm to handle this effectively. I need to process statements like these:
(a) # if(a)
(a,b) # if(a || b)
(a+b) # if(a && b)
(a+b,c) # same as ((a+b),c) or if((a&&b) || c)
(a,b+c) # same as (a,(b|c)) or if(a || (b&&c))
So the + operator takes precedence over the , operator. (so my + is like mathematical multiplication with , being mathematical addition, but that is just confusing).
I think a recursive function would be best, so I can handle nested parentheses nice and easy by a recursive call. I'll also take care of error handling once the function returns, so no worries there. The problems I'm having:
I just don't know how to tackle the precedence thing. I could return true as soon as I see a , and the previous value was true. Otherwise, I'll rerun the same routine. A plus would effectively be a bool multiplication (ie true*true=true, true*false=false etc...).
Error detection: I've thought up several schemes to handle the input, but there are a lot of ugly bad things I want to detect and print an error to the user. None of the schemes I thought of handle errors in a unified (read: centralized) place in the code, which would be nice for maintainability and readability:
()
(,...
(+...
(a,,...
(a,+...
(a+,...
(a++...
Detecting these in my "routine" above should take care of bad input. Of course I'll check end-of-input each time I read a token.
Of course I'll have the problem of maybe having o read the full text file if there are unmatched parenthesis, but hey, people should avoid such tension.
EDIT: Ah, yes, I forgot the ! which should also be usable like the classic not operator:
(!a+b,c,!d)
Tiny update for those interested: I had an uninformed wild go at this, and wrote my own implementation from scratch. It may not be pretty enough for the die-hards, so hence this question on codereview.
The shunting-yard algorithm is easily implementable in a relatively short amount of code. It can be used to convert an infix expression like those in your examples into postfix expressions, and evaluation of a postfix expression is Easy-with-a-capital-E (you don't strictly need to complete the infix-to-postfix conversion; you can evaluate the postfix output of the shunting yard directly and just accumulate the result as you go along).
It handles operator precedence, parentheses, and both unary and binary operators (and with a little effort can be modified to handle infix ternary operators, like the conditional operator in many languages).
Write it in yacc (bison) it becomes trivial.
/* Yeacc Code */
%token IDENTIFIER
%token LITERAL
%%
Expression: OrExpression
OrExpression: AndExpression
| OrExpression ',' AndExpression
AndExpression: NotExpression
| AndExpression '+' NotExpression
NotExpression: PrimaryExpression
| '!' NotExpression
PrimaryExpression: Identifier
| Literal
| '(' Expression ')'
Literal: LITERAL
Identifier: IDENTIFIER
%%
There's probably a better (there's definitely a more concise) description of this, but I learned how to do this from this tutorial many years ago:
http://compilers.iecc.com/crenshaw/
It's a very easy read for non-programmers too (like me). You'll need only the first few chapters.