Calculation of arithmetic expressions

Source: Internet
Author: User
The Calculation of arithmetic expressions in a computer is implemented through stacks. This section first discusses two Representation Methods of arithmetic expressions, namely, the infix representation and the suffix representation. Then, it discusses the algorithm for evaluating the suffix expression. Finally, it discusses the algorithm for converting an infix expression to a suffix expression.
1. Two arithmetic expressions
Generally, the written arithmetic expression is a sub-formula connected by the operand (also called an operation object or calculation amount), operators, and parentheses that change the operation order. The operands can be constants, variables, functions, and expressions. There are two types of operators: a single object operator and a binary object operator. A single object operator requires only one operand and is placed before the operand. A binary object operator requires two operands, and placed in the middle of the two operands. The single object operator is positive + and negative-. The binary operator is plus +, minus, multiplication, and division. For convenience, we will only consider binary operators in our discussion.
For example, for an arithmetic expression 2 + 5*6, the two operands of the multiplication operator '*' are 5 and 6 on both sides of the arithmetic expression. For the two operands of the addition operator '+, one is 2 before it, and the other is the result of 5*6 after it is 30. We refer to the habit of appearing a binary operator in the middle of two operands, which is called an infix expression or an infix expression.
The computation of an infix expression is complex. It must comply with the following three rules:
(1) Calculate the inside brackets and then the outside brackets;
(2) In parentheses or same-layer brackets, perform the multiplication and division operation first, and then perform the addition and subtraction operation. That is, the multiplication and division operation has a higher priority than the addition and subtraction operation;
(3) perform the same priority operation from left to right.
From these three rules, we can see that in the process of calculating the infix expression, we must consider both the role of parentheses, the priority of operators, and the order of the operators. Therefore, the actual operation order of operators is often different from the order they appear in the expression, which is unpredictable. Of course, by intuitively determining which operator in an infix expression is the first and which operator is the second ,......, It is not difficult to calculate the final algorithm, but it is difficult to process it through a computer, because the computer can only scan one character and one character. Which operator to calculate first, the whole infix expression must be scanned once. In principle, the number of operators in a infix expression must be scanned several times before the computation is completed. This is a waste of time, obviously, it is not advisable.
So can we convert the infix arithmetic expression into another form of arithmetic expression to simplify the computation? The answer is yes. Lukasiewicz, a Polish scientist, has long proposed another expression of arithmetic expressions, that is, suffix representation, or inverse Polish representation, the operator is defined after two calculation objects. An arithmetic expression indicated by a suffix is called a suffix arithmetic expression or a suffix expression. There are no parentheses in the suffix expression, and there is no difference in priority. The calculation process is based on the order in which operators appear. The entire calculation process can be completed only after scanning, it is much easier to calculate than the infix expression. For example, for the suffix expression 12! 4! -! 5! /, Where '! 'Character represents the space between components. Because the subtraction operator is in front and the Division operator is in the rear, subtraction should be performed first, followed by Division. The two operands of subtraction are the first 12 and 4, where the first number 12 is the subtrahend, and the second number 4 is the subtrahend. The two operands of division are the first 12 minus 4 (that is, 8) and 5, where 8 is the divisor, 5 is the divisor.
The rule for converting an infix arithmetic expression to a corresponding suffix arithmetic expression is to move each operator to the end of its two arithmetic objects, and then delete all the parentheses.
For example, for the following infix expressions:
(1) 3/5 + 6
(2) 16-9*(4 + 3)
(3) 2 * (x + y)/(3o)
(4) (25 + x) * (A * (a + B)
The corresponding suffix expressions are:
(1) 3! 5! /! 6! +
(2) 16! 9! 4! 3! +! *! -
(3) 2! X! Y! +! *! 1! X! -! /
(4) 25! X! +! A! A! B! +! *! B! +! *

2. suffix expression evaluate Algorithm
The suffix expression is easy to evaluate. You can scan it once. It needs to use a stack. Assume that the element type is represented by S. Assume that the element type is the type of the operand. Assume that the element type is float, use this stack to store the operands in the suffix expression, intermediate results in the calculation process, and final results. Assume that a suffix arithmetic expression uses '@' as the Terminator and is provided as a string. The basic idea of the suffix expression evaluate algorithm is to define a string containing a suffix arithmetic expression as an input string Stream object and read one character (space is used as the delimiter between data, when it is not read as a character), if it is an operator, it indicates that its two operands are already in stack s, where the top element of the stack is the last operand of the operator, the next element on the top of the stack is the first operand of the operator. After they are popped up, perform corresponding operations, and then press the operation results into Stack S. Otherwise, the character to be read must be the highest digit of the operand. You should send it back to the input stream, input the next data as a floating point number, and press it into Stack S. Scan each character in sequence (only scan the highest bit of a floating point number and input the entire floating point number at a time) and perform the above processing until the ending sign '@' is reached, indicating that the suffix expression is calculated, the final result is saved in the stack, and only this value exists in the stack. Just pop it up and return it. Specific Algorithm Description: Float compute (char * Str)
// Calculate the value of the suffix expression represented by the STR string,
// The expression must end with the '@' character.
...{
Stack s; // uses the S stack to store the operations and intermediate calculation results
Initstack (s); // initialize the stack
Istrstream ins (STR); // define STR as the input string Stream object INS
Char ch; // used to input characters
Float X; // used to input floating point numbers
INS> CH; // read one character in sequence from the INS Stream object (that is, the STR string)
While (Ch! = '@')
... {// Scan and process each character
Switch (CH)
...{
Case '+ ':
X = POP (s) + POP (s );
Break;
Case '-':
X = POP (s); // POP (s) pop-up Subtraction
X = POP (S)-X; // POP (s) displays the subtrahend.
Break;
Case '*':
X = POP (s) * Pop (s );
Break;
Case '/':
X = POP (s); // POP (s) pop-up Divisor
If (X! = 0.0)
X = POP (s)/X; // POP (s) pops up the dividend
Else... {// stop running when the divisor is 0
Cerr <"divide by 0! "<Exit (1 );
}
Break;
Default: // The highest digit of a floating point number.
INS. putback (CH); // send it back to the input stream.
INS> X; // read a floating point number from the string input stream.
}
Push (S, x); // read a floating point or perform corresponding operations
// The result is pushed into the S stack.
INS> CH; // enter the next character for the next round of loop Processing
}
If (! Stackempty (s ))
... {// If there is only one element in the stack, It is the value of the suffix expression, otherwise it is an error
X = POP (s );
If (stackempty (s ))
Return X;
Else ...{
Cerr <"expression error! "<Exit (1 );
}
}
Else... {// if the last stack is empty, stop running
Cerr <"Stack is empty! "<Exit (1 );
}
}

The running time of this algorithm is mainly spent on the while loop. It scans every data in the suffix expression from start to end (each operand or operator is a data). If the suffix expression is composed of n data, the time complexity of this algorithm is O (n ). The temporary space occupied by this algorithm during running mainly depends on the size of stack S. Obviously, its maximum depth does not exceed the number of operands in the expression, because the number of operands is equal to the number of operators (assuming '@' is also regarded as a special operator, that is, the end operator, therefore, the space complexity of this algorithm is also O (n ).
Assume that a string a is:
Char A [30] = "12 3 20 4/* 8-6 * + @";
If the corresponding infix arithmetic expression is 12 + (3 * (20/4)-8) * 6 @, the output result obtained by calling the above function using the following statement is 54.
Cout <in the process of evaluating this suffix arithmetic expression, starting from the fourth operand into the stack, after each operand or operator is processed, the operands stored in stack S and intermediate results are shown in Figure 4-4.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.