-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBVP.py
99 lines (82 loc) · 2.18 KB
/
BVP.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from scipy.linalg import solveh_banded
import matplotlib.pyplot as plt
# Two point BVP integraters
# solveBVP1 solves PDE of form, -u"(x) = f(x), 0 < x < 1, u(0) = u(1)= 0
# solveBVP2 solves PDE of form, -u"(x) + u(x) = f(x), 0 < x < 1, u(0) = u(1) = 0
# Sample PDEs provided at end
# Inputs
# f : ODE, must be of specified form above
# N : numer of steps
def solveBVP1(f,N):
# calc step size
h = 1/N
# set boundary conditions
y0 = 0
yN = 0
# define nodes
x = np.linspace(0, 1, N)
# define internal nodes
x_int = x[1:N-1]
# create LHS (banded) matrix
n_mat = N - 2
Ah = np.zeros((2, n_mat))
# Fill banded matrix Ab
Ah[0][:] = -1
Ah[1][:] = 2
# multiply Ah by 1/h^2
Ah = Ah * (1/h**2)
# create RHS matrix
b = np.zeros((N-2,1))
# fill RHS with f(x_int)
for i in range(n_mat):
b[i] = f(x_int[i])
# solve system
y_int = solveh_banded(Ah,b)
output = np.append(y0, y_int)
output = np.append(output, yN)
# plot solns
plt.plot(x,output)
plt.title("Fin Diff Approximation for " + f.__name__)
plt.title("N =" + str(N), loc = 'left')
return output
# Inputs
# f : ODE, must be of specified form above
# N : numer of steps
def solveBVP2(f, N):
# calc step size
h = 1/N
# set boundary conditions
y0 = 0
yN = 0
# define nodes
x = np.linspace(0, 1, N)
# define internal nodes
x_int = x[1:N-1]
# create LHS (banded) matrix
n_mat = N - 2
Ah = np.zeros((2, n_mat))
# Fill banded matrix Ab
Ah[0][:] = -1
Ah[1][:] = 2 - (h**2)
# create RHS matrix
b = np.zeros((N-2,1))
# fill RHS with f(x_int)
for i in range(n_mat):
b[i] = f(x_int[i]) * h**2
# solve system
y_int = solveh_banded(Ah,b)
output = np.append(y0, y_int)
output = np.append(output, yN)
# plot solns
plt.plot(x,output)
plt.title("Fin Diff Approximation for " + f.__name__)
plt.title("N =" + str(N), loc = 'left')
return output
# Sample ODEs
def f1(x):
return 1
def f2(x):
return x**2