optimized gain calculation