File size: 4,294 Bytes
0389c8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import sympy as sp
import numpy as np
import matplotlib.pyplot as plt

x, y = sp.symbols('x y')


def generate_polynomial_template(degree):
    terms = [f"a{i}*x^{degree - i}" for i in range(degree)] + [f"a{degree}"]
    return " + ".join(terms) + " = 0"


def solve_polynomial(degree, coeff_string):
    try:
        coeffs = [sp.sympify(s) for s in coeff_string.strip().split()]
        if len(coeffs) != degree + 1:
            return f"โš ๏ธ Please enter exactly {degree + 1} coefficients.", None, None, ""

        poly = sum([coeffs[i] * x**(degree - i) for i in range(degree + 1)])
        simplified = sp.simplify(poly)

        # Step-by-step factorization
        factored_steps = []
        current_expr = simplified
        while True:
            factored = sp.factor(current_expr)
            if factored == current_expr:
                break
            factored_steps.append(factored)
            current_expr = factored

        roots = sp.solve(sp.Eq(simplified, 0), x)
        root_display = []
        for i, r in enumerate(roots):
            r_simplified = sp.nsimplify(r, rational=True)
            root_display.append(f"r_{{{i+1}}} = {sp.latex(r_simplified)}")

        steps_output = f"### ๐Ÿง Polynomial Expression\n\n$$ {sp.latex(poly)} = 0 $$\n\n"
        steps_output += f"### โœ๏ธ Simplified\n\n$$ {sp.latex(simplified)} = 0 $$\n\n"

        if factored_steps:
            steps_output += "### ๐Ÿชœ Step-by-Step Factorization\n\n"
            for i, step in enumerate(factored_steps, 1):
                steps_output += f"**Step {i}:** $$ {sp.latex(step)} = 0 $$\n\n"
        else:
            steps_output += "### ๐Ÿคท No further factorization possible\n\n"

        steps_output += "### ๐Ÿฅฎ Roots\n\n$$ " + " \\quad ".join(root_display) + " $$"

        # Plotting
        f_lambdified = sp.lambdify(x, simplified, modules=["numpy"])
        x_vals = np.linspace(-10, 10, 400)
        y_vals = f_lambdified(x_vals)

        fig, ax = plt.subplots(figsize=(6, 4))
        ax.plot(x_vals, y_vals, label="Polynomial")
        ax.axhline(0, color='black', linewidth=0.5)
        ax.axvline(0, color='black', linewidth=0.5)
        ax.set_title("๐Ÿ“ˆ Graph of the Polynomial")
        ax.set_xlabel("x")
        ax.set_ylabel("f(x)")
        ax.grid(True)

        real_roots = [sp.N(r.evalf()) for r in roots if sp.im(r) == 0]
        for r in real_roots:
            ax.plot([float(r)], [0], 'ro', label="Real Root")

        ax.legend()

        return steps_output, fig, "", steps_output

    except Exception as e:
        return f"โŒ Error: {e}", None, "", ""


def solve_linear_system(eq1_str, eq2_str):
    try:
        eq1 = sp.sympify(eq1_str)
        eq2 = sp.sympify(eq2_str)

        sol = sp.solve((eq1, eq2), (x, y), dict=True)

        steps = "### ๐Ÿ” Solving System\n\n"
        steps += f"**Equation 1:** $$ {sp.latex(eq1)} $$\n\n"
        steps += f"**Equation 2:** $$ {sp.latex(eq2)} $$\n\n"

        if sol:
            sol = sol[0]
            steps += f"**Solution:** $$ x = {sp.latex(sol[x])}, \\quad y = {sp.latex(sol[y])} $$\n\n"
        else:
            steps += "**โŒ No unique solution or inconsistent system**\n"

        # Plotting
        x_vals = np.linspace(-10, 10, 400)
        f1 = sp.solve(eq1, y)
        f2 = sp.solve(eq2, y)

        fig, ax = plt.subplots(figsize=(6, 4))
        if f1 and f2:
            y1_vals = sp.lambdify(x, f1[0], modules=["numpy"])(x_vals)
            y2_vals = sp.lambdify(x, f2[0], modules=["numpy"])(x_vals)
            ax.plot(x_vals, y1_vals, label="Equation 1")
            ax.plot(x_vals, y2_vals, label="Equation 2")

            if sol:
                px = float(sp.N(sol[x]))
                py = float(sp.N(sol[y]))
                ax.plot(px, py, 'ro')
                ax.annotate(f"({px:.2f}, {py:.2f})", (px, py), textcoords="offset points", xytext=(10, 5),
                            ha='center', color='red')

        ax.axhline(0, color='black', linewidth=0.5)
        ax.axvline(0, color='black', linewidth=0.5)
        ax.set_title("๐Ÿ“‰ Graph of the Linear System")
        ax.set_xlabel("x")
        ax.set_ylabel("y")
        ax.grid(True)
        ax.legend()

        return steps, fig, steps

    except Exception as e:
        return f"โŒ Error: {e}", None, ""