Actualización de la historia de cálculos con nuevas ecuaciones y valores. Mejora en la lógica de resolución iterativa y auto-aplicación de soluciones en el motor algebraico. Ajuste en la configuración de la interfaz y eliminación de pruebas obsoletas.
This commit is contained in:
parent
53dd4eb801
commit
f0bdf1e419
|
@ -1,9 +1,11 @@
|
|||
|
||||
|
||||
y = x + 3
|
||||
z = y + x
|
||||
solve(x)
|
||||
solve(z)
|
||||
y = 2*x + 3
|
||||
x = z * 4
|
||||
z = 8
|
||||
y=?
|
||||
z=?
|
||||
|
||||
|
||||
x=?
|
||||
# Instanciación via sympify
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"window_geometry": "1020x700+356+1216",
|
||||
"sash_pos_x": 343,
|
||||
"sash_pos_x": 347,
|
||||
"symbolic_mode": true,
|
||||
"show_numeric_approximation": true,
|
||||
"keep_symbolic_fractions": true,
|
||||
|
|
|
@ -370,18 +370,30 @@ class PureAlgebraicEngine:
|
|||
except Exception as e:
|
||||
return f"Error resolviendo sistema: {e}"
|
||||
elif len(args) == 1 and hasattr(args[0], 'is_Symbol') and args[0].is_Symbol:
|
||||
# solve(variable) - resolver para una variable específica y devolver ecuación
|
||||
# solve(variable) - resolver para una variable específica y auto-aplicar
|
||||
var_symbol = args[0]
|
||||
solution_value = self._solve_for_variable(var_symbol)
|
||||
|
||||
# Si encontramos una solución, devolver como ecuación
|
||||
# Si encontramos una solución, auto-aplicar al sistema
|
||||
if solution_value != var_symbol:
|
||||
return Eq(var_symbol, solution_value)
|
||||
# Resolver iterativamente para obtener el valor más simplificado
|
||||
final_value = self._resolve_iteratively(solution_value)
|
||||
|
||||
# Auto-aplicar la solución al sistema
|
||||
self._auto_apply_solution(var_symbol, final_value)
|
||||
|
||||
# Verificar que el resultado no sea problemático
|
||||
if final_value == var_symbol or str(final_value) in ['True', 'False']:
|
||||
return var_symbol
|
||||
|
||||
return Eq(var_symbol, final_value)
|
||||
else:
|
||||
# Si no hay solución en las ecuaciones, verificar en symbol_table
|
||||
var_name = str(var_symbol)
|
||||
if var_name in self.symbol_table:
|
||||
return Eq(var_symbol, self.symbol_table[var_name])
|
||||
value = self.symbol_table[var_name]
|
||||
final_value = self._resolve_iteratively(value)
|
||||
return Eq(var_symbol, final_value)
|
||||
else:
|
||||
return var_symbol
|
||||
else:
|
||||
|
@ -475,6 +487,80 @@ class PureAlgebraicEngine:
|
|||
self.logger.debug(f"Error resolviendo {var_symbol}: {e}")
|
||||
return var_symbol
|
||||
|
||||
def _resolve_iteratively(self, expression, max_iterations=10):
|
||||
"""Resuelve una expresión iterativamente sustituyendo valores conocidos"""
|
||||
try:
|
||||
current_expr = expression
|
||||
|
||||
for iteration in range(max_iterations):
|
||||
# Sustituir valores del symbol_table
|
||||
substituted = current_expr
|
||||
|
||||
# Sustituir cada variable conocida por su valor
|
||||
for var_name, value in self.symbol_table.items():
|
||||
var_symbol = sp.Symbol(var_name)
|
||||
if var_symbol in substituted.free_symbols:
|
||||
# Resolver recursivamente el valor antes de sustituir
|
||||
resolved_value = self._resolve_iteratively(value, max_iterations - iteration - 1) if iteration < max_iterations - 1 else value
|
||||
substituted = substituted.subs(var_symbol, resolved_value)
|
||||
|
||||
# Si no hay cambio, hemos terminado
|
||||
if substituted == current_expr:
|
||||
break
|
||||
|
||||
current_expr = substituted
|
||||
|
||||
# Simplificar el resultado
|
||||
if hasattr(current_expr, 'simplify'):
|
||||
current_expr = simplify(current_expr)
|
||||
|
||||
# Si llegamos a un valor numérico, terminar
|
||||
if current_expr.is_number:
|
||||
break
|
||||
|
||||
return current_expr
|
||||
|
||||
except Exception as e:
|
||||
self.logger.debug(f"Error en resolución iterativa: {e}")
|
||||
return expression
|
||||
|
||||
def _auto_apply_solution(self, var_symbol, solution_value):
|
||||
"""Auto-aplica una solución al sistema como si fuera una nueva asignación"""
|
||||
try:
|
||||
var_name = str(var_symbol)
|
||||
|
||||
# 1. Actualizar symbol_table
|
||||
self.symbol_table[var_name] = solution_value
|
||||
|
||||
# 2. Buscar y actualizar/reemplazar ecuaciones existentes
|
||||
updated_equations = []
|
||||
equation_found = False
|
||||
|
||||
for eq in self.equations:
|
||||
if eq.lhs == var_symbol or eq.rhs == var_symbol:
|
||||
# Reemplazar la ecuación existente
|
||||
new_eq = Eq(var_symbol, solution_value)
|
||||
updated_equations.append(new_eq)
|
||||
equation_found = True
|
||||
else:
|
||||
updated_equations.append(eq)
|
||||
|
||||
# 3. Si no había ecuación para esta variable, agregar una nueva
|
||||
if not equation_found:
|
||||
new_eq = Eq(var_symbol, solution_value)
|
||||
updated_equations.append(new_eq)
|
||||
|
||||
# 4. Actualizar la lista de ecuaciones
|
||||
self.equations = updated_equations
|
||||
|
||||
# 5. Asegurar que la variable esté en el conjunto de variables
|
||||
self.variables.add(var_symbol)
|
||||
|
||||
self.logger.debug(f"Auto-aplicada solución: {var_symbol} = {solution_value}")
|
||||
|
||||
except Exception as e:
|
||||
self.logger.debug(f"Error auto-aplicando solución: {e}")
|
||||
|
||||
def _get_numeric_approximation(self, expr) -> Optional[str]:
|
||||
"""Obtiene aproximación numérica si es posible"""
|
||||
try:
|
||||
|
|
|
@ -1,25 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test final con el ejemplo exacto del usuario
|
||||
"""
|
||||
|
||||
import main_evaluation_puro
|
||||
|
||||
def test_ejemplo_usuario():
|
||||
print("=== EJEMPLO ORIGINAL DEL USUARIO ===")
|
||||
|
||||
engine = main_evaluation_puro.PureAlgebraicEngine()
|
||||
|
||||
casos = [
|
||||
"y = x + 3",
|
||||
"z = y + x",
|
||||
"solve(x)",
|
||||
"solve(z)"
|
||||
]
|
||||
|
||||
for caso in casos:
|
||||
result = engine.evaluate_line(caso)
|
||||
print(f"{caso} → {result.output}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_ejemplo_usuario()
|
Loading…
Reference in New Issue