|
| 1 | +import math |
| 2 | +import numpy as np |
| 3 | +import matplotlib.pyplot as plt |
| 4 | + |
| 5 | +def evaluate_expression(expr, x_val=None): |
| 6 | + """ |
| 7 | + Safely evaluate a mathematical expression. |
| 8 | + If x_val is provided, uses numpy functions to support array operations for graphing. |
| 9 | + """ |
| 10 | + # Allowed names for safe evaluation |
| 11 | + allowed_names = {k: v for k, v in math.__dict__.items() if not k.startswith("__")} |
| 12 | + allowed_names["abs"] = abs |
| 13 | + allowed_names["round"] = round |
| 14 | + |
| 15 | + if x_val is not None: |
| 16 | + allowed_names["x"] = x_val |
| 17 | + # Overwrite with numpy functions to handle arrays gracefully (e.g. sin(x) -> np.sin(x)) |
| 18 | + allowed_names.update({k: v for k, v in np.__dict__.items() if not k.startswith("__")}) |
| 19 | + |
| 20 | + try: |
| 21 | + # __builtins__ must be an empty dict to prevent accessing dangerous built-in functions |
| 22 | + result = eval(expr, {"__builtins__": {}}, allowed_names) |
| 23 | + return result |
| 24 | + except Exception as e: |
| 25 | + raise ValueError(f"Invalid expression: {e}") |
| 26 | + |
| 27 | + |
| 28 | +def main(): |
| 29 | + print("=" * 50) |
| 30 | + print("🧮 WELCOME TO SCIENTIFIC GRAPHING CALCULATOR 🧮") |
| 31 | + print("=" * 50) |
| 32 | + |
| 33 | + history = [] |
| 34 | + run = True |
| 35 | + |
| 36 | + while run: |
| 37 | + print("\n--------🧮 MENU 🧮---------") |
| 38 | + print('1. Standard Mode (Calculate expressions) ➕') |
| 39 | + print('2. Graphing Mode (Plot equations) 📉') |
| 40 | + print('3. View History 📜') |
| 41 | + print('4. Exit 🚪') |
| 42 | + |
| 43 | + user_choice = input('\n📌 Enter your choice (1-4): ').strip() |
| 44 | + |
| 45 | + if user_choice == '4': |
| 46 | + print('\n👋 Goodbye! Have a great day! 🌟\n') |
| 47 | + run = False |
| 48 | + break |
| 49 | + |
| 50 | + if user_choice == '3': |
| 51 | + if not history: |
| 52 | + print("📜 No calculations yet.") |
| 53 | + else: |
| 54 | + print("\n------ 📜 Calculation History 📜 ------") |
| 55 | + for item in history: |
| 56 | + print(item) |
| 57 | + continue |
| 58 | + |
| 59 | + if user_choice == '1': |
| 60 | + print("\n--- ➕ Standard Mode ---") |
| 61 | + print("Enter a mathematical expression (e.g., '2 + 3 * sin(pi/2)' or 'log(e)').") |
| 62 | + print("Type 'back' to return to the main menu.") |
| 63 | + while True: |
| 64 | + expr = input("\n🔢 Expression: ").strip() |
| 65 | + if expr.lower() == 'back': |
| 66 | + break |
| 67 | + if not expr: |
| 68 | + continue |
| 69 | + try: |
| 70 | + result = evaluate_expression(expr) |
| 71 | + print(f"✅ Result: {result}") |
| 72 | + history.append(f"{expr} = {result}") |
| 73 | + except Exception as e: |
| 74 | + print(f"❌ Error evaluating expression: {e}") |
| 75 | + |
| 76 | + elif user_choice == '2': |
| 77 | + print("\n--- 📉 Graphing Mode ---") |
| 78 | + print("Enter an equation in terms of 'x' (e.g., 'x**2 - 4*x + 4' or 'sin(x)').") |
| 79 | + print("Type 'back' to return to the main menu.") |
| 80 | + while True: |
| 81 | + expr = input("\n📉 Equation f(x) = ").strip() |
| 82 | + if expr.lower() == 'back': |
| 83 | + break |
| 84 | + if not expr: |
| 85 | + continue |
| 86 | + |
| 87 | + try: |
| 88 | + # Generate x values |
| 89 | + x = np.linspace(-10, 10, 400) |
| 90 | + |
| 91 | + # Evaluate the user's expression |
| 92 | + y = evaluate_expression(expr, x_val=x) |
| 93 | + |
| 94 | + # Handle cases where the expression evaluates to a scalar (e.g., "5") |
| 95 | + if np.isscalar(y): |
| 96 | + y = np.full_like(x, y) |
| 97 | + |
| 98 | + # Plotting |
| 99 | + plt.figure(figsize=(8, 6)) |
| 100 | + plt.plot(x, y, label=f"y = {expr}", color='blue') |
| 101 | + plt.title("Graphing Calculator") |
| 102 | + plt.xlabel("x") |
| 103 | + plt.ylabel("f(x)") |
| 104 | + |
| 105 | + # Add axis lines |
| 106 | + plt.axhline(0, color='black', linewidth=1) |
| 107 | + plt.axvline(0, color='black', linewidth=1) |
| 108 | + |
| 109 | + plt.grid(color='gray', linestyle='--', linewidth=0.5) |
| 110 | + plt.legend() |
| 111 | + |
| 112 | + print(f"📈 Showing plot for: y = {expr}. Close the plot window to continue.") |
| 113 | + plt.show() |
| 114 | + |
| 115 | + history.append(f"Graphed: y = {expr}") |
| 116 | + except Exception as e: |
| 117 | + print(f"❌ Error graphing equation: {e}") |
| 118 | + |
| 119 | + else: |
| 120 | + print('❌ Invalid choice. Please enter a number between 1 and 4.') |
| 121 | + |
| 122 | +if __name__ == "__main__": |
| 123 | + main() |
0 commit comments