RPN Square Root

Status
Not open for further replies.
Hello guys, I'm studying java and I recently discovered the RPN, I was wondering how do add a square root in an RPN?


EDIT: Figured it out XD hehe

EDIT: I THOUGHT I FIGURED IT OUT help
JavaScript:
public static double SolvePostfix(String[] tokens) {
        double returnValue = 0;
        String operators = "+-*/^%";

        Stack<String> stack = new Stack<String>();

        for (String t : tokens) {
            if (!operators.contains(t)) {
                stack.push(t);
            } else {double a = Double.valueOf(stack.pop());
               
                               
                                    double b = Double.valueOf(stack.pop());
                                    switch (t) {
                                        case "+":
                                                stack.push(String.valueOf(a + b));
                                                break;
                                        case "-":
                                                stack.push(String.valueOf(b - a));
                                                break;
                                        case "*":
                                                stack.push(String.valueOf(a * b));
                                                break;
                                        case "/":
                                                stack.push(String.valueOf(b / a));
                                                break;
                                        case "^":
                                                stack.push(String.valueOf(pow(a,b)));
                                                break;
                                        case "%":
                                                stack.push(String.valueOf(b%a));
                                                break;
                                    }
                           
            }
        }

How do I evaluate unary operators?
 
Last edited:
You need a way to differentiate between a normal minus and an unary one. Assuming your tokenizer knows the difference, simply use your own imaginary operator, which the solver then knows to use, by popping only one argument.

I'd do it by having an additional list for all unary operators (which, again, are any character you want), and after you get the first argument, check if the operator is unary or not, and respond appropriately.
 
I figured out why it doesn't work. It seems that the square root symbol can't be read, I replaced it with s and now it works.

EDIT: Now my problem is, What precedence and associativity will I give to the unary operators

EDIT 2: How can I make: x ( ( 1 - c ( 30 ) ) / 2 ) to postfix: 1 30 c - 2 / x, it gives me this postfix: 1 30 2 / c - x
 
Last edited:
Status
Not open for further replies.
Back
Top