optimized error function