Near-Optimal Approximation of Matrix Functions by the Lanczos Method