Move gravity calculation into a generic function

As discussed in #118.