sp.integrate
fails, it returns an sp.Integral
object.
We can test on this object and fall back on numerical integration.symbolic
to explicitly choose
between symbolic and numerical computing.
def least_squares(f, psi, Omega, symbolic=True):
...
for i in range(N+1):
for j in range(i, N+1):
integrand = psi[i]*psi[j]
if symbolic:
I = sp.integrate(integrand, (x, Omega[0], Omega[1]))
if not symbolic or isinstance(I, sp.Integral):
# Could not integrate symbolically,
# fall back on numerical integration
integrand = sp.lambdify([x], integrand)
I = sp.mpmath.quad(integrand, [Omega[0], Omega[1]])
A[i,j] = A[j,i] = I
integrand = psi[i]*f
if symbolic:
I = sp.integrate(integrand, (x, Omega[0], Omega[1]))
if not symbolic or isinstance(I, sp.Integral):
integrand = sp.lambdify([x], integrand)
I = sp.mpmath.quad(integrand, [Omega[0], Omega[1]])
b[i,0] = I
...