Issue
This is a heat equation integration problem.
So we have u(x,0)
, the initial condition, that we want to integrate, that is:
- x, when
0 <= x <= 10
- 20-x, when
10 <= x <= 20
Now, the problem is, if I want to calculate the integral of u(x,0)
from 0 to 20, if we use hand, it should be:
int_{0}^{10} x dx + int_{10}^{20} (20-x) dx
with Python' SymPy code this is what I can create, very manual (the integral of u(x,0)
from 0 to 20 is represented by function g
):
import numpy as np
import sympy as sm
from sympy import *
from spb import *
x = sm.symbols("x")
t = sm.symbols("t")
n = sm.symbols("n", integer=True)
L = 20
f1 = (2/L)*x*sin(n*np.pi*x/20)
f2 = (2/L)*(20-x)*sin(n*np.pi*x/20)
fint1 = sm.integrate(f1,(x,0,10))
fint2 = sm.integrate(f2,(x,10,20))
D = 0.475
g = (fint1+fint2)*sin(n*np.pi*x/20)*exp(-(n**2)*(np.pi**2)*D*t/400).nsimplify()
is there a SymPy' technique of integration for this case, so I do not need to write manually fint1
, fint2
, ... ?
Solution
You can use Piecewise
for this:
In [8]: f = (S(2)/L)*sin(n*pi*x/20)*Piecewise((x, (0 <= x) & (x <= 10)), (20-x, (10 < x) & (x <= 20)))
In [9]: f
Out[9]:
⎛⎧ x for x ≥ 0 ∧ x ≤ 10 ⎞ ⎛π⋅n⋅x⎞
⎜⎨ ⎟⋅sin⎜─────⎟
⎝⎩20 - x for x ≤ 20 ∧ x > 10⎠ ⎝ 20 ⎠
─────────────────────────────────────────
10
In [10]: piecewise_fold(f)
Out[10]:
⎧ ⎛π⋅n⋅x⎞
⎪ x⋅sin⎜─────⎟
⎪ ⎝ 20 ⎠
⎪ ──────────── for x ≥ 0 ∧ x ≤ 10
⎪ 10
⎨
⎪ ⎛π⋅n⋅x⎞
⎪(20 - x)⋅sin⎜─────⎟
⎪ ⎝ 20 ⎠
⎪─────────────────── for x ≤ 20 ∧ x > 10
⎩ 10
Now you can integrate the Piecewise expression once:
In [11]: integrate(f, (x, 0, 20))
Out[11]:
⎧ ⎛π⋅n⎞
⎪80⋅sin⎜───⎟
⎪ ⎝ 2 ⎠
⎪─────────── for n ≠ 0
⎨ 2 2
⎪ π ⋅n
⎪
⎪ 0 otherwise
⎩
Answered By - Oscar Benjamin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.