0

The code I have written to integrate is giving wrong results.I get the c_0,c_1,...c_4 to be zeros! What am I doing wrong? I am using simply 0.7.6 on a mac.

from numpy import *
from matplotlib.pyplot import *
from sympy import *
x = Symbol('x')
f = 1.0*sin(np.pi * x)
phi_0 = 1.0
phi_1 = 1.0*x
phi_2 = 1./2*(3*x**2-1)
phi_3 = 1./2*(5*x**3-3*x)
phi_4 = 1./8*(35*x**4-30*x**2+3)
c_0 = integrate(f*phi_0, (x, -1.0, 1.0))
c_1 = integrate(f*phi_1, (x, -1.0, 1.0))
c_2 = integrate(f*phi_2, (x, -1.0, 1.0))
c_3 = integrate(f*phi_3, (x, -1.0, 1.0))
c_4 = integrate(f*phi_4, (x, -1.0, 1.0))
print c_0
print c_1
print c_2
print c_3
print c_4

2 Answers 2

1

Other than the need to import numpy as np, I don't see any problems in the most recent version (0.7.6). Some values are zero (as expected due to symmetry consideration) but others are not:

>>> print c_0
0
>>> print c_1
0.636619772367581
>>> print c_2
0
>>> print c_3
-0.330926260628403
>>> print c_4
0
Sign up to request clarification or add additional context in comments.

4 Comments

I get zeros for all @smichr .
For me, >>> sympy.__version__ -> '0.7.6-git'. What do you get?
Also, check your value of np.pi. It is possible that it got set to 0 which would then make your f zero, too.
how can I check my version? I typed "sympy.__version__ -> " in my code but got an error. @smichr
1

I agree with smichr. Everything appears to be fine as long as your import numpy. You can also use scipy but that is dependent on your preferences and needs.

from scipy.integrate import quad

quad(lambda x: x**2, 0, 1)

4 Comments

can I define x**2 prior to calling quad?
Yeah that's not a problem. For example lets say f(x) was defined to be x**2, you can say quad(f, -1, 1) and it should integrate that for you
how should I define f. before I would define x as symbolic variable and then define f. Now what should I use? lambda? @dparadis28
You could use lambdas or define a function (ex: def f(x): return x**2) and use f as an arg for the quad function as shown above; quad(f, -1, 1). Does this help point you in the right direction?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.