Transform Integral to Loss Function

Hi there,
This question is about loss function.
I have an integral equation which is shown below:


where y(x) is a one dimension vector. I want to use the above equation as my loss function, and here is my solution. I use matrix multiplication to rewrite it:

def my_loss (yhat, x, matrix):
    L = len(yhat)

    first_term = (2 * pi / L) * (torch.mm(yhat.T, torch.log(yhat)))
    second_term = (4 * pi ** 2/ L ** 2) * torch.mm(torch.mm(yhat.T, matrix), yhat)

    loss = first_term + second_term
    return loss

It works and the training result is not bad, but I find that the above code will cause a little bit of error. for example: if the y(x) = sin(x)**2, the integral vaule of first term is -1.21358, but the vector multiplication will gives me -1.2041.
Does anyone know better ways to do this job?