0
$\begingroup$

I have tried to do a trapeze integration with f(x)=x^2, where I know how the antiderivative looks like, so F(x) = (1/3)x^3

Here's my code, just like I tried:

x = np.arange(-10,10, 0.01)   # start,stop,step
f = x**2

l=it.cumtrapz(f,x, initial=0)

plt.plot(l)

Then I get this plot (1):

enter image description here

But the plot should look like this (2). The axis designations are different and the intersection point in the coordinate origin (0,0) is not the same as in (1).:

enter image description here

How can I achieve with my code that the graph from (1) looks exactly like (2)?

$\endgroup$
  • 2
    $\begingroup$ You need to do plt.plot(x,l). Otherwise, it assumes x starts at 0. $\endgroup$ – Tyberius Jun 25 at 12:54
1
$\begingroup$

You are approximating a definite integral with cumtrapz it won't give you the same result as the integrated equation unless you add a constant and plot with the given x coordinates:

import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as it

x = np.arange(-10,10, 0.01)   # start,stop,step
f = x**2

f_int=it.cumtrapz(f,x, initial=0)
plt.plot(x, (1/3) * np.power(x,3))                                                                                                                       
plt.plot(x, f_int + (1/3) * np.power(-10,3), '--')                                                                                                       
plt.legend(["(1/3) x^3", "cumtrapz(x^2) + C"])                                                                                                           
| cite | improve this answer | |
$\endgroup$

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.