2

I am trying to use SciPy to integrate this function:

y(x) = (e^-ax)*cos(x) between 0 and 4pi.

Here is the code I have so far:

from numpy import *
from scipy.integrate import simps
a = 0 
x = linspace(0 , 4*pi, 100)
y = (e^-(a*x))*cos(x)
integral_value = simps(y,x)
print integral_value

However it doesn't seem to be working. Any help would be appreciated, thanks!

1
  • 'don't seem to be working' is not the correct way to ask a question. Tell us what is wrong, such as error messages or values to don't match your expectations. Commented Mar 10, 2017 at 16:50

3 Answers 3

5

Well if you run the program you obtain the following error:

TypeError: ufunc 'bitwise_xor' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

So you know the problem is with the ^ (bitwise xor) in your function. In Python one uses ** to take the exponent.

If one writes:

y = (e**-(a*x))*cos(x)

instead, one gets:

>>> print integral_value
-0.000170200006112

The full program:

from numpy import *
from scipy.integrate import simps
a = 0 
x = linspace(0 , 4*pi, 100)
y = (e**-(a*x))*cos(x)
integral_value = simps(y,x)
print integral_value

You can also make explicit use of numpy functions with:

from numpy import *
from scipy.integrate import simps
a = 0 
x = linspace(0 , 4*pi, 100)
y = exp(-a*x)*cos(x)
integral_value = simps(y,x)
print integral_value

In order to increase the precision, you can increase the number of points (100 is not that much).

Sign up to request clarification or add additional context in comments.

2 Comments

I don't think Simpson's is necessary.
@BillBell: it is indeed easy to symbolically integrate this. But one can also be intersted in how stable numerical integration is. Or what the effect of Monte Carlo and quasi Monte Carlo integration is for instance.
1
import numpy as np
import math
from scipy.integrate import simps
a = 0
x = np.linspace(0 , 4*math.pi, 100)

#create a vectorized function which can be applied directly to an array    
fn = np.vectorize(lambda x: math.exp(-a*x)*math.cos(x))
y = fn(x)

integral_value = simps(y, x)
print integral_value

this indeed yields value of -0.000170200006112. Note that for a=0, the integral is equal to zero, so in order to get "closer" you would need to refine the grid...

Comments

1

Cracking a nut with a sledgehammer ...

>>> from sympy import *
>>> var('a x')
(a, x)
>>> y = exp(-a*x)*cos(x)
>>> y.subs(a,0)
cos(x)

Should it surprise any of us to find that this integrates to 0 (zero) over the given interval?

Comments

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.