# Large numerical error using trapz

I need to perform some basic numerical integrations in pytorch and am currently investigating feasible methods. As a validity check for using the new `torch.trapz` function, I implemented the Matlab example on multiple numerical integration:

``````import torch

dx = 0.1
x = torch.arange(-3, 3, dx)
y = torch.arange(-5, 5, dx)
X, Y = torch.meshgrid(x, y)

F = X**2 + Y**2

result = torch.trapz(torch.trapz(F, dx=dx, dim=0), dx=dx, dim=0)
# Returns tensor(646.9882)
``````

The result is quite far away from what Matlab produces (680.200) and the exact value of 680. Is this expected? If yes, why so?

What would be a simple alternative to using `torch.trapz`?

1 Like

I also found that torch.trapz gives a slightly wrong estimate in:

``````import torch  # Import PyTorch

samples = 100000
x = torch.linspace(-5, 5, samples)
y = x**2

integral = 0  # Initialise integral = 0
for i in range(0, samples-1):
integral = integral + (0.5*(y[i]+y[i+1])*(x[i+1]-x[i]))

integral2 = torch.trapz(y,x)

print(integral-integral2)
print(torch.isclose(integral, integral2))
``````