-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmath_handler.py
More file actions
693 lines (602 loc) · 30.6 KB
/
math_handler.py
File metadata and controls
693 lines (602 loc) · 30.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
import sympy
import numpy as np
import re
from latex2sympy2 import latex2sympy
from typing import Dict, Union, List, Tuple
class MathHandler:
def __init__(self):
"""Initialize the math handler with common mathematical symbols."""
# Initialize sympy symbols for common variables
self.x, self.y, self.z = sympy.symbols('x y z')
def parse_polynomial(self, expression: str) -> List[Tuple[float, int]]:
"""
Parse a polynomial expression into a list of (coefficient, power) tuples.
Example: "x^3 + 2x^2 - 5x + 3" -> [(1,3), (2,2), (-5,1), (3,0)]
"""
# Clean up the input string
expression = expression.lower().strip()
# Remove derivative-related words
for word in ['derivative of', 'differentiate', 'd/dx', 'calculate']:
expression = expression.replace(word, '').strip()
# Add '+' before negative terms for easier splitting
expression = expression.replace('- ', '+ -')
if expression.startswith('+ '):
expression = expression[2:]
# Split into terms
terms = expression.split(' + ')
result = []
for term in terms:
term = term.strip()
if not term:
continue
# Handle constant terms
if term.replace('-', '').replace('.', '').isdigit():
result.append((float(term), 0))
continue
# Extract coefficient and power
coeff = 1.0
power = 1
# Handle negative terms
if term.startswith('-'):
coeff = -1.0
term = term[1:]
# Parse coefficient if present
if term[0].isdigit():
parts = term.split('x')
coeff *= float(parts[0])
term = 'x' + (parts[1] if len(parts) > 1 else '')
# Parse power if present
if '^' in term:
power = int(term.split('^')[1])
result.append((coeff, power))
return sorted(result, key=lambda x: x[1], reverse=True) # Sort by power in descending order
def parse_math_expression(self, expression: str) -> Tuple[bool, Union[str, sympy.Expr]]:
"""
Parse a mathematical expression from text format.
Returns (success, result/error_message)
"""
try:
# Try parsing as a polynomial first
terms = self.parse_polynomial(expression)
if not terms:
return False, "Could not parse the expression. Please check the format."
# Convert to sympy expression
x = sympy.Symbol('x')
expr = sum(coeff * x**power for coeff, power in terms)
return True, expr
except Exception as e:
print(f"Parse error: {str(e)}")
return False, "Could not parse the expression. Please use a format like 'x^3 + 2x^2 - 5x + 3'"
# Extract the main expression and any limit information
limit_info = None
if 'lim' in expression or 'limit' in expression:
# Handle various limit expression formats
for pattern in [
r'limit of (.*) as .* approaches (.*)',
r'lim .*?->(.+?) (.*)',
r'lim.+?(\w+).+?approaches (.+?) of (.+)',
r'.*as (\w+) (?:approaches|goes to) (.+?) (?:of )?(.*)',
r'.*approaches (.+)' # Simple format for just the limit point
]:
import re
match = re.search(pattern, expression)
if match:
groups = match.groups()
if len(groups) == 1: # Simple format
limit_point = groups[0]
# Remove the limit part from expression
expression = re.sub(r'.*approaches.*', '', expression).strip()
limit_info = {'point': limit_point}
elif len(groups) == 2:
limit_point, expr = groups
expression = expr
limit_info = {'point': limit_point}
elif len(groups) == 3:
var, point, expr = groups
expression = expr
limit_info = {'var': var, 'point': point}
break
if not limit_info: # If no pattern matched but 'limit' or 'lim' is present
# Assume it's approaching 0 by default for common limits
limit_info = {'point': '0'}
# Clean up the expression by removing limit-related words
expression = re.sub(r'limit of|lim|as .* approaches.*|when .* approaches.*', '', expression).strip()
# Clean up the expression
expression = expression.strip()
# Create symbol and handle basic replacements
x = sympy.Symbol('x')
# Handle basic trigonometric functions
for trig_func in ['sin', 'cos', 'tan']:
if trig_func in expression.lower():
expression = expression.replace(f'{trig_func}(x)', f'sympy.{trig_func}(x)')
expression = expression.replace(f'{trig_func}x', f'sympy.{trig_func}(x)')
# Handle special functions and constants
replacements = {
'sin(': 'sympy.sin(',
'cos(': 'sympy.cos(',
'tan(': 'sympy.tan(',
'exp(': 'sympy.exp(',
'log(': 'sympy.log(',
'ln(': 'sympy.log(',
'^': '**',
'pi': 'sympy.pi',
'e': 'sympy.E'
}
for old, new in replacements.items():
expression = expression.replace(old, new)
# Handle division
if '/' in expression:
num, denom = expression.split('/', 1)
# Ensure proper handling of complex expressions
num = f"({num})" if any(c in num for c in '()+- ') else num
denom = f"({denom})" if any(c in denom for c in '()+- ') else denom
try:
expr = sympy.sympify(f"{num}/{denom}")
except:
# If sympify fails, try creating the expression directly
if 'sin' in num.lower():
expr = sympy.sin(x) / sympy.Symbol(denom)
else:
raise
else:
expr = sympy.sympify(expression)
# If this is a limit expression, return with limit info
if limit_info:
return True, (expr, limit_info)
return True, expr
except Exception as e:
print(f"Parse error: {str(e)}")
return False, f"Could not parse the mathematical expression. Please use a simpler format like 'x^2 + 2*x + 1 = 0'"
def solve_equation(self, equation: str) -> Dict[str, Union[str, List[str]]]:
"""
Solve a mathematical equation and return the result with step-by-step explanation.
"""
try:
# Clean up the equation
equation = equation.strip()
# Handle equation solving
if '=' in equation:
left, right = equation.split('=')
# Parse both sides of the equation
success_left, left_expr = self.parse_math_expression(left)
success_right, right_expr = self.parse_math_expression(right)
if not (success_left and success_right):
return {"error": "Invalid equation format. Please use a format like 'x^2 + 2*x + 1 = 0'"}
# Create equation and get steps
equation_expr = sympy.Eq(left_expr, right_expr)
steps = []
# Step 1: Standard form (ax² + bx + c = 0)
standard_form = left_expr - right_expr
expanded = sympy.expand(standard_form)
steps.append({
"description": "Rearrange to standard form (ax² + bx + c = 0)",
"latex": sympy.latex(expanded) + " = 0"
})
# Step 2: Factor if possible
factored = sympy.factor(expanded)
if factored != expanded:
steps.append({
"description": "Factor the equation",
"latex": sympy.latex(factored) + " = 0"
})
# Step 3: Calculate discriminant for quadratic equations
if expanded.as_poly().degree() == 2:
a, b, c = sympy.Poly(expanded, sympy.Symbol('x')).all_coeffs()
discriminant = b**2 - 4*a*c
steps.append({
"description": "Calculate discriminant (b² - 4ac)",
"latex": f"\\Delta = {sympy.latex(discriminant)}"
})
# Step 4: Solve
solution = sympy.solve(equation_expr)
formatted_solutions = []
for sol in solution:
if isinstance(sol, (int, float)):
latex_sol = str(sol)
else:
latex_sol = sympy.latex(sol)
formatted_solutions.append(f"x = {latex_sol}")
# Step 5: Verify solutions
verifications = []
x = sympy.Symbol('x')
for sol in solution:
verified = expanded.subs(x, sol)
verifications.append({
"description": f"Verify solution x = {sympy.latex(sol)}",
"latex": f"{sympy.latex(expanded)}|_{{x={sympy.latex(sol)}}} = {sympy.latex(verified)}"
})
return {
"type": "equation",
"solution": formatted_solutions,
"latex": sympy.latex(equation_expr),
"steps": steps,
"verifications": verifications
}
else:
# Try parsing as an expression to solve
success, expr = self.parse_math_expression(equation)
if not success:
return {"error": expr}
# Handle expression evaluation with steps
steps = []
# Step 1: Original expression
steps.append({
"description": "Original expression",
"latex": sympy.latex(expr)
})
# Step 2: Expand if needed
expanded = sympy.expand(expr)
if expanded != expr:
steps.append({
"description": "Expand the expression",
"latex": sympy.latex(expanded)
})
# Step 3: Simplify
result = sympy.simplify(expanded)
if result != expanded:
steps.append({
"description": "Simplify",
"latex": sympy.latex(result)
})
return {
"type": "expression",
"result": str(result),
"latex": sympy.latex(result),
"steps": steps
}
except Exception as e:
return {"error": "Please provide a valid equation in the format 'x^2 + 2*x + 1 = 0'"}
def calculate_derivative(self, expression: str, variable: str = 'x') -> Dict[str, Union[str, List[str]]]:
"""
Calculate the derivative of a polynomial expression with step-by-step explanation.
"""
try:
# Parse the polynomial expression
terms = self.parse_polynomial(expression)
if not terms:
return {"error": "Could not parse the expression. Please use a format like 'x^3 + 2x^2 - 5x + 3'"}
steps = []
derivative_terms = []
# Step 1: Show original expression
x = sympy.Symbol('x')
original_expr = sum(coeff * x**power for coeff, power in terms)
steps.append({
"description": "Original polynomial",
"latex": sympy.latex(original_expr)
})
# Step 2: Apply power rule to each term
for coeff, power in terms:
if power == 0:
# Derivative of a constant is 0
steps.append({
"description": f"The derivative of the constant term {coeff}",
"latex": f"\\frac{{d}}{{dx}}({coeff}) = 0"
})
else:
# Apply power rule: d/dx(ax^n) = a*n*x^(n-1)
new_coeff = coeff * power
new_power = power - 1
derivative_terms.append((new_coeff, new_power))
steps.append({
"description": f"Apply the power rule to the term {coeff}x^{power}",
"latex": f"\\frac{{d}}{{dx}}({coeff}x^{{{power}}}) = {coeff} \\cdot {power} \\cdot x^{{{new_power}}} = {new_coeff}x^{{{new_power}}}"
})
# Step 3: Combine terms for the final derivative
derivative = sum(coeff * x**power for coeff, power in derivative_terms)
steps.append({
"description": "Combine all terms to get the final derivative",
"latex": sympy.latex(derivative)
})
# Add final explanation of the power rule
steps.append({
"description": "Final derivative using power rule",
"latex": f"\\frac{{d}}{{dx}}({sympy.latex(original_expr)}) = {sympy.latex(derivative)}"
})
return {
"type": "derivative",
"result": str(derivative),
"latex": sympy.latex(derivative),
"steps": steps,
"original_expression": sympy.latex(original_expr)
}
except Exception as e:
return {"error": f"Error calculating derivative: {str(e)}"}
def calculate_integral(self, expression: str, variable: str = 'x') -> Dict[str, Union[str, List[str]]]:
"""
Calculate the indefinite integral of an expression with step-by-step explanation.
"""
try:
success, expr = self.parse_math_expression(expression)
if not success:
return {"error": expr}
var = sympy.Symbol(variable)
steps = []
# Step 1: Show original expression
steps.append({
"description": "Original expression to integrate",
"latex": f"\\int {sympy.latex(expr)} \\, d{variable}"
})
# Step 2: Apply integration rules
integral = sympy.integrate(expr, var)
expanded_integral = sympy.expand(integral)
# Add explanation of which integration rule was applied
if expr.is_polynomial():
steps.append({
"description": "Apply power rule: ∫x^n dx = (x^(n+1))/(n+1) + C",
"latex": f"\\int {sympy.latex(expr)} \\, d{variable} = {sympy.latex(integral)} + C"
})
elif expr.has(sympy.sin) or expr.has(sympy.cos):
steps.append({
"description": "Apply trigonometric integration rules",
"latex": f"\\int {sympy.latex(expr)} \\, d{variable} = {sympy.latex(integral)} + C"
})
elif expr.has(sympy.exp):
steps.append({
"description": "Apply exponential rule: ∫e^x dx = e^x + C",
"latex": f"\\int {sympy.latex(expr)} \\, d{variable} = {sympy.latex(integral)} + C"
})
else:
steps.append({
"description": "Apply integration rules",
"latex": f"\\int {sympy.latex(expr)} \\, d{variable} = {sympy.latex(integral)} + C"
})
# Step 3: Simplify if possible
if expanded_integral != integral:
steps.append({
"description": "Simplify the result",
"latex": f"{sympy.latex(expanded_integral)} + C"
})
return {
"type": "integral",
"result": str(expanded_integral) + " + C",
"latex": sympy.latex(expanded_integral) + " + C",
"steps": steps
}
except Exception as e:
return {"error": f"Error calculating integral: {str(e)}"}
def evaluate_limit(self, expression: str) -> Dict[str, Union[str, List[dict]]]:
"""
Evaluate the limit of an expression as the variable approaches a point with step-by-step explanation.
"""
try:
steps = []
x = sympy.Symbol('x')
# Clean up the expression
expression = expression.lower().strip()
# Special case: sin(x)/x as x approaches 0
sin_x_pattern = any(pattern in expression for pattern in ['sin(x)/x', 'sinx/x', 'sin x/x'])
if sin_x_pattern and ('0' in expression or 'approaches 0' in expression):
steps.append({
"description": "This is a special case: sin(x)/x as x approaches 0",
"latex": "\\lim_{x \\to 0} \\frac{\\sin(x)}{x}"
})
steps.append({
"description": "This is a fundamental limit in calculus",
"latex": "\\lim_{x \\to 0} \\frac{\\sin(x)}{x} = 1"
})
return {
"type": "limit",
"result": "1",
"latex": "1",
"steps": steps
}
# Parse expression with limit information
success, result = self.parse_math_expression(expression)
if not success:
return {"error": result}
# Extract expression and limit information
if isinstance(result, tuple):
expr, limit_info = result
if 'var' in limit_info:
var = sympy.Symbol(limit_info['var'])
else:
var = x # Default to x if not specified
# Handle limit point conversion
try:
point_str = limit_info['point'].strip()
if point_str == 'infinity' or point_str == 'inf':
limit_point = sympy.oo
elif point_str == '-infinity' or point_str == '-inf':
limit_point = -sympy.oo
else:
limit_point = float(point_str)
except (ValueError, TypeError):
limit_point = 0 # Default to 0 if conversion fails
else:
# If no limit info was extracted, use defaults
expr = result
var = x
limit_point = 0.0
# Step 1: Show original expression
steps.append({
"description": "Original limit expression",
"latex": f"\\lim_{{{var.name} \\to {limit_point}}} {sympy.latex(expr)}"
})
# Step 2: Handle special cases like sin(x)/x
if expr.has(sympy.sin) and expr.is_rational_function():
steps.append({
"description": "This is a special limit involving trigonometric functions",
"latex": f"\\text{{Special case: }}{sympy.latex(expr)}"
})
# For sin(x)/x specifically
if isinstance(expr, sympy.Mul) and len(expr.args) == 2:
if sympy.sin(var) in expr.args and 1/var in expr.args:
steps.append({
"description": "For sin(x)/x, this is a well-known limit that equals 1",
"latex": "\\lim_{x \\to 0} \\frac{\\sin(x)}{x} = 1"
})
# Step 3: Substitute values near the limit point
try:
h_values = [0.1, 0.01, 0.001]
evaluations = []
for h in h_values:
# For better numerical stability with trigonometric functions
if abs(limit_point) < 1e-10: # If approaching 0
# Evaluate from both sides for limits at 0
point_left = -float(h)
point_right = float(h)
try:
value_left = float(expr.subs(var, point_left).evalf())
value_right = float(expr.subs(var, point_right).evalf())
# Use the average for better accuracy
value = (value_left + value_right) / 2
if abs(value) < 1e10: # Avoid very large numbers
evaluations.append({'h': h, 'point': h, 'value': value})
except:
continue
else:
point = float(limit_point - h)
try:
value = float(expr.subs(var, point).evalf())
if abs(value) < 1e10: # Avoid very large numbers
evaluations.append({'h': h, 'point': point, 'value': value})
except:
continue
if evaluations:
# Format the table of values
table_rows = []
for eval in evaluations:
table_rows.append(
f"{var.name} = {eval['point']:.6f}: {eval['value']:.6f}"
)
steps.append({
"description": f"Evaluate values approaching {var.name} = {limit_point}",
"latex": "\\begin{align*}" + " \\\\ ".join(table_rows) + "\\end{align*}"
})
except Exception as e:
print(f"Error in numerical evaluation: {str(e)}")
# For complex limits like sin(x)/x, suggest using a different tool
if (isinstance(expr, sympy.Mul) and sympy.sin(var) in expr.free_symbols and var in expr.free_symbols):
return {
"error": "This type of limit (sin(x)/x) requires specialized handling. Please use a graphing calculator or mathematical software specifically designed for these calculations."
}
# Step 5: Apply algebraic manipulation if needed
expanded = sympy.expand(expr)
if expanded != expr:
steps.append({
"description": "Expand the expression",
"latex": f"\\lim_{{{var.name} \\to {limit_point}}} {sympy.latex(expanded)}"
})
# Step 6: Apply L'Hôpital's rule if needed
if expr.is_rational_function():
num, denom = sympy.fraction(expr)
try:
num_limit = sympy.limit(num, var, limit_point)
denom_limit = sympy.limit(denom, var, limit_point)
if (num_limit == 0 and denom_limit == 0) or \
(sympy.oo in (num_limit, denom_limit) and sympy.oo in (num_limit, denom_limit)):
steps.append({
"description": "This is an indeterminate form, applying L'Hôpital's rule",
"latex": "\\text{Apply L'Hôpital's rule by taking derivatives}"
})
# Apply L'Hôpital's rule
num_derivative = sympy.diff(num, var)
denom_derivative = sympy.diff(denom, var)
expr = num_derivative / denom_derivative
steps.append({
"description": "After applying L'Hôpital's rule",
"latex": f"\\lim_{{{var.name} \\to {limit_point}}} \\frac{{{sympy.latex(num_derivative)}}}{{{sympy.latex(denom_derivative)}}}"
})
except Exception as e:
print(f"Error applying L'Hôpital's rule: {str(e)}")
# Step 6: Calculate the final limit
limit = sympy.limit(expr, var, limit_point)
# Handle different types of limits
if limit == sympy.oo:
steps.append({
"description": "The limit approaches positive infinity",
"latex": f"\\lim_{{{var.name} \\to {limit_point}}} {sympy.latex(expr)} = +\\infty"
})
elif limit == -sympy.oo:
steps.append({
"description": "The limit approaches negative infinity",
"latex": f"\\lim_{{{var.name} \\to {limit_point}}} {sympy.latex(expr)} = -\\infty"
})
elif limit.is_finite:
steps.append({
"description": "The limit exists and equals",
"latex": f"\\lim_{{{var.name} \\to {limit_point}}} {sympy.latex(expr)} = {sympy.latex(limit)}"
})
else:
steps.append({
"description": "The limit does not exist",
"latex": "\\text{DNE (Does Not Exist)}"
})
return {
"type": "limit",
"result": str(limit),
"latex": sympy.latex(limit),
"steps": steps
}
except Exception as e:
return {"error": f"Error evaluating limit: {str(e)}"}
def format_response(self, result: Dict[str, Union[str, List[str]]]) -> str:
"""
Format the mathematical result into a user-friendly response with proper LaTeX formatting
and enhanced visual presentation.
"""
if "error" in result:
return f"❌ {result['error']}"
latex_parts = ["📐 Mathematical Solution\n"]
latex_parts.append("=" * 40 + "\n") # Visual separator
if result.get("type") == "equation":
solutions = result["solution"]
if not solutions:
return "This equation has no solution."
# Add original equation with clear formatting
equation_latex = result.get('latex', '')
latex_parts.append("📝 Original Equation:")
latex_parts.append("$" + equation_latex + "$")
latex_parts.append("\n" + "-" * 30 + "\n") # Subtle separator
# Add solution steps with enhanced formatting
if "steps" in result:
latex_parts.append("🔍 Step-by-Step Solution:\n")
for i, step in enumerate(result["steps"], 1):
latex_parts.append(f"Step {i}: {step['description']}")
# Add box around the mathematical expression for better visibility
latex_parts.append("$\\boxed{" + step['latex'] + "}$")
latex_parts.append("") # Add spacing between steps
latex_parts.append("-" * 30 + "\n")
# Add solutions with clear formatting
if len(solutions) == 1:
latex_parts.append("💡 Final Solution:")
latex_parts.append("$\\boxed{" + solutions[0] + "}$")
else:
latex_parts.append("💡 Final Solutions:")
solutions_latex = [f"$\\boxed{{{s}}}$" for s in solutions]
latex_parts.append(" , ".join(solutions_latex))
# Add solution verification with enhanced presentation
if "verifications" in result:
latex_parts.append("\n✅ Verification:")
for verify in result["verifications"]:
latex_parts.append(verify['description'])
latex_parts.append("$\\boxed{" + verify['latex'] + "}$")
latex_parts.append("")
else:
# For non-equation results (expressions, derivatives, limits, etc.)
result_str = result.get('result', 'No result available')
latex_output = result.get('latex', '')
# Add type-specific header
type_headers = {
"derivative": "📊 Derivative Calculation",
"integral": "∫ Integral Calculation",
"limit": "→ Limit Evaluation",
"expression": "🔢 Expression Evaluation"
}
header = type_headers.get(result.get("type", "expression"), "Mathematical Calculation")
latex_parts.append(f"{header}\n")
# Add step-by-step explanation with enhanced formatting
if "steps" in result:
latex_parts.append("🔍 Step-by-Step Process:\n")
for i, step in enumerate(result["steps"], 1):
latex_parts.append(f"Step {i}: {step['description']}")
# Add box around the mathematical expression
latex_parts.append("$\\boxed{" + step['latex'] + "}$")
latex_parts.append("") # Add spacing between steps
# Add final result with clear formatting
latex_parts.append("💡 Final Result:")
if latex_output:
latex_parts.append("$\\boxed{" + latex_output + "}$")
else:
latex_parts.append(result_str)
return "\n".join(latex_parts)