Optimizing density calculation