added a more efficient way to calculate the error