## Solve y'' = 2*x/(1+x^2)*y' - 2/(1+x^2) * y + 1
## with y(0) = 1.25 and y(4) = -0.95 on the interval [0, 4]:
f1 <- function(x) 2*x / (1 + x^2)
f2 <- function(x) -2 / (1 + x^2)
f3 <- function(x) rep(1, length(x)) # vectorized constant function 1
x <- c(0.0, 4.0)
y <- c(1.25, -0.95)
sol <- bvp(f1, f2, f3, x, y)
plot(sol$xs, sol$ys, ylim = c(-2, 2),
xlab = "", ylab = "", main = "Boundary Value Problem")
# The analytic solution is
sfun <- function(x) 1.25 + 0.4860896526*x - 2.25*x^2 +
2*x*atan(x) - 1/2 * log(1+x^2) + 1/2 * x^2 * log(1+x^2)
xx <- linspace(0, 4)
yy <- sfun(xx)
lines(xx, yy, col="red")
grid()
## Solve -y'' + 0.1*y = 1 + sin(4*pi*x)
## on [0, 1] with y(0) = y(1) = 0.
f3 <- function(x) -sin(4*pi*x) - 1
sol <- bvp(0, 0.1, f3, c(0, 1), c(0, 0), n = 40)
# The analytic solution is
fan <- function(x) cc[1]*exp(sqrt(0.1)*x) + cc[2]*exp(-sqrt(0.1)*x) +
1/((4*pi)^2+0.1)*sin(4*pi*x) + 10
ezplot(fan, 0, 1, col = "magenta", lty = 3)
points(sol$xs, sol$ys, type = "p", col = "blue")
grid()
Run the code above in your browser using DataLab