While using Multivariate normal distribution in PyTorch I decided to compare it with exact analytical expression.
To my surprise, there was a small difference between them.
Is there any reason for this behaviour?
Firstly, calculate probabilities using MultivariateNormal:
1 from torch.distributions.multivariate_normal import MultivariateNormal
2 import torch
3 sigma = 2
4 m = MultivariateNormal(torch.zeros(2, dtype=torch.float32), torch.eye(2, dtype=torch.float32)*sigma**2)
5 values_temp = torch.zeros(size=(1,2), dtype=torch.float32)
6 out_torch = torch.exp(m.log_prob(values_temp))
7 out_torch
Out: tensor([0.0398])
Secondly, one can write exact formula for this case:
1 import numpy as np
2 out_exact = 1/(2*np.pi*sigma**2) * torch.exp(-torch.pow(values_temp, 2).sum(dim=-1)/(2*sigma**2))
3 out_exact
Out: tensor([0.0398])
There is a difference between them:
1 (out_torch - out_exact).sum()
Out: tensor(3.7253e-09)
Can someone help me understand the behavior of these two snippets? Which of these two expressions is more precise? Maybe someone can underline my mistake in any part of the code?