#include <Arduino.h>
#include <math.h> // Include for sin, cos, tan, atan, asin, acos, log, log10, exp, etc.
// Define PI and e as constants using double precision
const double PIii = 3.14159265358979323846264338327950288419716939937510;
const double E = 2.71828182845904523536028747135266249775724709369995; // Euler's number
// Declaration for infix to postfix conversion and evaluation
class CharStack {
private:
String* arr; // Changed to String to handle function names
int capacity;
int top;
public:
CharStack(int size) : capacity(size), arr(new String[size]), top(-1) {}
~CharStack() { delete[] arr; }
void push(String element) { if (top < capacity - 1) arr[++top] = element; }
String pop() { return top >= 0 ? arr[top--] : ""; }
String peek() { return top >= 0 ? arr[top] : ""; }
bool isEmpty() { return top < 0; }
};
class FloatStack {
private:
double* arr; // Use double to store values for double precision
int top;
public:
FloatStack(int size) : arr(new double[size]), top(-1) {}
~FloatStack() { delete[] arr; }
void push(double element) { arr[++top] = element; }
double pop() { return arr[top--]; }
bool isEmpty() const { return top < 0; }
};
// Optimized power function to handle integer exponents efficiently
double power(double base, double exp) {
// Special cases
if (exp == 0) return 1; // Any number raised to 0 is 1
if (exp == 1) return base; // Any number raised to 1 is the number itself
if (base == 0) return 0; // 0 raised to any number is 0 (except 0^0, which is undefined)
// Check if exponent is an integer
if (floor(exp) == exp) {
int n = (int)exp;
double result = 1.0;
bool isNegative = (n < 0); // Handle negative exponents
n = abs(n); // Work with positive exponent for now
// Exponentiation by squaring for integer exponents
while (n > 0) {
if (n % 2 == 1) {
result *= base; // If the exponent is odd, multiply the base
}
base *= base; // Square the base
n /= 2; // Divide the exponent by 2
}
return isNegative ? 1.0 / result : result; // Handle negative exponents
}
// For non-integer exponents, use the standard pow function
return pow(base, exp);
}
String infixToPostfix(String infix);
int precedence(String op);
bool isOperator(char c);
double evaluatePostfix(const String& postfix);
String addZeroBeforeUnaryMinus(const String& infix);
double convertToRadians(double angle);
double convertToDegrees(double radians); // Function to convert radians to degrees
bool useRadians = true; // Global flag for radian or degree mode
void setup() {
Serial.begin(9600);
while (!Serial); // Wait for Serial to initialize
// Ask the user if they want to use radians or degrees
Serial.println("Choose mode: Enter 'r' for Radians or 'd' for Degrees:");
while (!Serial.available()) {
// Wait for the user to enter 'r' or 'd'
}
char mode = Serial.read();
useRadians = (mode == 'r'); // Set mode based on input
Serial.println("Enter an infix expression:");
}
void loop() {
if (Serial.available() > 0) {
String infix = Serial.readStringUntil('\n');
infix.trim();
// Display the original infix expression
Serial.print("Infix: ");
Serial.println(infix);
String postfix = infixToPostfix(infix);
// Display the postfix expression
Serial.print("Postfix: ");
Serial.println(postfix);
double result = evaluatePostfix(postfix);
Serial.print("Result: ");
Serial.println(result, 15); // Print result with 15 decimal places for precision
Serial.println("Enter another infix expression:");
}
}
String addZeroBeforeUnaryMinus(const String& infix) {
String modifiedInfix = "";
bool lastWasOperatorOrStart = true;
for (unsigned int i = 0; i < infix.length(); ++i) {
char ch = infix[i];
if (ch == '-' && lastWasOperatorOrStart) {
modifiedInfix += "(0-";
i++;
while (i < infix.length() && (isdigit(infix[i]) || infix[i] == '.')) {
modifiedInfix += infix[i];
i++;
}
i--;
modifiedInfix += ")";
} else {
modifiedInfix += ch;
}
lastWasOperatorOrStart = isOperator(ch) || ch == '(';
}
return modifiedInfix;
}
String infixToPostfix(String infix) {
infix = addZeroBeforeUnaryMinus(infix);
CharStack operatorStack(100);
String postfix = "";
bool expectOperand = true;
for (int i = 0; i < infix.length(); i++) {
char currentChar = infix[i];
if (infix.substring(i, i + 3) == "sin" || infix.substring(i, i + 3) == "cos" || infix.substring(i, i + 3) == "tan") {
operatorStack.push(infix.substring(i, i + 3));
i += 2; // Skip past "sin", "cos", or "tan"
expectOperand = true;
} else if (infix.substring(i, i + 4) == "asin" || infix.substring(i, i + 4) == "acos" || infix.substring(i, i + 4) == "atan") {
operatorStack.push(infix.substring(i, i + 4));
i += 3; // Skip past "asin", "acos", or "atan"
expectOperand = true;
} else if (infix.substring(i, i + 3) == "exp") { // Add support for "exp"
operatorStack.push("exp");
i += 2; // Skip past "exp"
expectOperand = true;
} else if (infix.substring(i, i + 2) == "ln") { // Add support for "ln"
operatorStack.push("ln");
i += 1; // Skip past "ln"
expectOperand = true;
} else if (infix.substring(i, i + 3) == "log") { // Add support for "log"
operatorStack.push("log");
i += 2; // Skip past "log"
expectOperand = true;
} else if (infix.substring(i, i + 7) == "antilog") { // Add support for "antilog"
operatorStack.push("antilog");
i += 6; // Skip past "antilog"
expectOperand = true;
} else if (infix.substring(i, i + 2) == "pi") {
postfix += String(PIii, 15); // Use double precision for pi
postfix += ' ';
expectOperand = false;
i++;
} else if (infix[i] == 'e') { // Detect Euler's number 'e'
postfix += String(E, 15); // Use double precision for e
postfix += ' ';
expectOperand = false;
} else if (isdigit(currentChar) || (currentChar == '-' && expectOperand)) {
if (currentChar == '-') {
postfix += '0';
postfix += ' ';
}
postfix += currentChar;
while (i + 1 < infix.length() && (isdigit(infix[i + 1]) || infix[i + 1] == '.')) {
postfix += infix[++i];
}
postfix += ' ';
expectOperand = false;
} else if (isOperator(currentChar)) {
while (!operatorStack.isEmpty() && precedence(operatorStack.peek()) >= precedence(String(currentChar))) {
postfix += operatorStack.pop();
postfix += ' ';
}
operatorStack.push(String(currentChar));
expectOperand = true;
} else if (currentChar == '(') {
operatorStack.push(String(currentChar));
expectOperand = true;
} else if (currentChar == ')') {
while (!operatorStack.isEmpty() && operatorStack.peek() != "(") {
postfix += operatorStack.pop();
postfix += ' ';
}
operatorStack.pop(); // Remove '(' from the stack
expectOperand = false;
}
}
while (!operatorStack.isEmpty()) {
postfix += operatorStack.pop();
postfix += ' ';
}
postfix.trim();
return postfix;
}
int precedence(String op) {
if (op == "+" || op == "-") return 1;
if (op == "*" || op == "/" || op == "%") return 2;
if (op == "^") return 3; // ^ has higher precedence
if (op == "sin" || op == "cos" || op == "tan" || op == "asin" || op == "acos" || op == "atan" || op == "ln" || op == "log" || op == "exp" || op == "antilog") return 4; // Added exp here
return -1;
}
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '%' || c == '^';
}
double convertToRadians(double angle) {
if (useRadians) return angle;
return angle * (PIii / 180.0); // Convert degrees to radians with double precision
}
// Function to convert radians to degrees
double convertToDegrees(double radians) {
return radians * (180.0 / PIii);
}
double evaluatePostfix(const String& postfix) {
FloatStack stack(50);
int i = 0;
while (i < postfix.length()) {
if (postfix[i] == ' ') {
i++;
continue;
}
if (isOperator(postfix[i])) {
double val2 = stack.pop();
double val1 = stack.pop();
switch (postfix[i]) {
case '+': stack.push(val1 + val2); break;
case '-': stack.push(val1 - val2); break;
case '*': stack.push(val1 * val2); break;
case '/': stack.push(val1 / val2); break;
case '^': stack.push(power(val1, val2)); break; // Use right-associative exponentiation
}
} else if (isdigit(postfix[i]) || postfix[i] == '.') {
String numStr = "";
while (i < postfix.length() && (isdigit(postfix[i]) || postfix[i] == '.')) {
numStr += postfix[i++];
}
stack.push(numStr.toDouble()); // Push double value
continue;
} else if (postfix.substring(i, i + 3) == "sin") {
stack.push(sin(convertToRadians(stack.pop()))); // Use double precision for sin
i += 3;
} else if (postfix.substring(i, i + 3) == "cos") {
stack.push(cos(convertToRadians(stack.pop()))); // Use double precision for cos
i += 3;
} else if (postfix.substring(i, i + 3) == "tan") {
stack.push(tan(convertToRadians(stack.pop()))); // Use double precision for tan
i += 3;
} else if (postfix.substring(i, i + 4) == "asin") {
double value = asin(stack.pop()); // Get result in radians
stack.push(useRadians ? value : convertToDegrees(value)); // Convert to degrees if needed
i += 4;
} else if (postfix.substring(i, i + 4) == "acos") {
double value = acos(stack.pop()); // Get result in radians
stack.push(useRadians ? value : convertToDegrees(value)); // Convert to degrees if needed
i += 4;
} else if (postfix.substring(i, i + 4) == "atan") {
double value = atan(stack.pop()); // Get result in radians
stack.push(useRadians ? value : convertToDegrees(value)); // Convert to degrees if needed
i += 4;
} else if (postfix.substring(i, i + 2) == "ln") {
double value = stack.pop();
stack.push(log(value)); // Use log() for natural logarithm (ln)
i += 2;
} else if (postfix.substring(i, i + 3) == "log") {
double value = stack.pop();
stack.push(log10(value)); // Use log10() for log base 10
i += 3;
} else if (postfix.substring(i, i + 3) == "exp") {
double value = stack.pop();
stack.push(exp(value)); // Use exp() for e^x (ln^-1)
i += 3;
} else if (postfix.substring(i, i + 7) == "antilog") {
double value = stack.pop();
stack.push(pow(10, value)); // Use pow(10, x) for antilog base 10
i += 7;
}
i++;
}
return stack.pop(); // Final result is double precision
}