Recently, I have sometimes needed an analytical solution of a polynomial that satisfies certain boundary conditions. Finding an analytical solution seemed to be difficult, so I tried to find out if it could be made easier using SymPy.

SymPy

SymPy is a python library for performing symbolic operations. You can do the following:

For example, suppose you want to find the analytical solution of the following simultaneous equations. $ bx + ay = ab $ $ x - cy = c$ The solution of this simultaneous equation is

```
import sympy
a = sympy.symbols("a")
b = sympy.symbols("b")
c = sympy.symbols("c")
x = sympy.symbols("x")
y = sympy.symbols("y")
sympy.solve([b*x+a*y-b*a,x-c*y-c],(x,y))
```

The result is $ \ frac {ac \ left (b + 1 \ right)} {a + bc}, \ frac {b \ left (a --c \ right)} {a + bc} $. It can be obtained.

Here, the polynomial

among,

```
for i in range(6):
exec(f"A{i} = sympy.Symbol(\"A{i}\")")
S1 = sympy.Symbol("S1")
x = sympy.Symbol("x")
f = A0 + A1*(x) + A2*(x)**2 + A3*(x)**3 + A4*(x)**4 + A5*(x)**5
f1 = sympy.diff(f, x)
f2 = sympy.diff(f1, x)
```

First, prepare the variables and the function you want to find as above,

The condition of $ f (0) = 0 $ is

```
cond0 = f.subs(x, 0) - 0
```

It is expressed as. Similarly, all the remaining conditions

```
cond1 = f.subs(x, 1) - S1
cond2 = f1.subs(x, 0) - 0
cond3 = f1.subs(x, 1) - 0
cond4 = f2.subs(x, 0) - 0
cond5 = f2.subs(x, 1) - 0
```

Defined in.

$ A_ {0}, A_ {1}, A_ {2}, A_ {3}, A_ {4}, A_ {5} $ that satisfy all of these conditions

```
solution = sympy.solve([cond0, cond1, cond2, cond3, cond4, cond5],(A0,A1,A2,A3,A4,A5))
```

Then the answer is

Substituting this result into $ f (x) $

```
for i in range(6):
exec(f"f = f.subs(A{i}, solution[A{i}])")
```

And now we know the function $ f (x) $ we want to find.

Recommended Posts