i need some help, i have an assignment to code an integration of a function using simpsons rule. I need to use the inbuilt scipy integratesimps function to plot a 1D graph. I just don't know where to start. I think i have to get a list/array of each value of y for the function that corresponds to each values of x: e.g
if my function is x^2 then when x is 0 y is 0, x is 1 y is 1, x is 2 y is 4, and so on up to a huge limit...
and then use integrate.simps(y,x) where y are all the y values as shown above and x are all the corresponding x values.
However, i can't get it to work at all...has anyone got any examples of a graph plot for a function of x^2 using integrate.simps(y,x)?
here is what i've got so far:
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
x = np.linspace(-10,10,N)
N = 100
yarray = []
def f(x):
return x**2
for i in x :
y = f(i)
yarray.append(y)
print(yarray)
E = integrate.simps(yarray,x)
print(E)
plt.plot(x,E)
Basically, you need to calculate the integral value for every range of x, from [-10,-10] to [-10,10]
This example code plots
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
def f(x):
return x**2
N = 100
x = np.linspace(-10,10,N)
integrals = []
x_range = []
y_range = []
for i in x:
x_range.append(i)
y_range.append(f(i))
integral = integrate.simps(y_range, x_range)
integrals.append(integral)
plt.plot(x, integrals)
plt.show()
To wrap it up
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
def integrals(f, xs):
x_range = []
y_range = []
results = []
for x in xs:
x_range.append(x)
y_range.append(f(x))
integral = integrate.simps(y_range, x_range)
results.append(integral)
return results
def f(x, b):
return (x-b)**2
xs = np.linspace(-10, 10, 100)
plt.plot(xs, integrals(lambda x: f(x, 0), xs), label='b=0')
plt.plot(xs, integrals(lambda x: f(x, 2), xs), label='b=2')
plt.plot(xs, integrals(lambda x: f(x, 4), xs), label='b=4')
plt.title('$y(x) = \int_{-10}^{x}(t-b)^2dt$')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()