# How to use cumtrapz correctly?

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):

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).:

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

• You need to do plt.plot(x,l). Otherwise, it assumes x starts at 0. – Tyberius Jun 25 '20 at 12:54

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"])