Nonlinear ODE Statement I would like to use scipy to solve the following:

u'' + (u')^2 = sin(x)

where u = u(x).

Approach I am looking at the following link


Problem - Not sure about variable wrt x or How to input BC's

The example given in the link does not include a term wrt x, in particular not sure how to include


from the right hand side of my problem, nor the


Work Done

In the following I try to modify the example from the above link to conform to my ODE above

   from scipy.integrate import *
import numpy as np

from numpy import *
def fun(x, y):
    return np.vstack((y[1],np.sin(x) -(y[0])**2))
def bc(ya, yb):
    return np.array([ya[0], yb[0]-1])
x = np.linspace(0, 1, 5)
y_a = np.zeros((2, x.size))
y_b = np.zeros((2, x.size))
y_b[0] = 3

from scipy.integrate import solve_bvp
res_a = solve_bvp(fun, bc, x, y_a)
res_b = solve_bvp(fun, bc, x, y_b)
x_plot = np.linspace(0, 1, 100)
y_plot_a = res_a.sol(x_plot)[0]
y_plot_b = res_b.sol(x_plot)[0]
import matplotlib.pyplot as plt
plt.plot(x_plot, y_plot_a, label='y_a')
plt.plot(x_plot, y_plot_b, label='y_b')
  • $\begingroup$ Could you add what you actually find questionable about your result? Apart from not using the correct DE as per answer. You also should check res.success or print res.message, as it is not unlikely that something goes wrong with the convergence of the BVP solver. Also explore the tol parameter, the default is rather high. $\endgroup$ – Lutz Lehmann Jan 6 '19 at 23:14

I think in NumPy, if y is a matrix, y[0] gets you the 0-th row, but it usually makes the code clearer if you use y[0,:].

The primary problem I see is that in fun you're defining the ODE $$ u''+u^2=\sin x, $$ using y[0,:] instead of y[1,:].


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.