Spectroscopic techniques based on Larmor precession of particle spins require that for all trajectories of a diverging beam the path integral of the modulus of the magnetic field must be a constant. The amount of precession performed by each spin is then a function of the particle energy only. For cylinder magnets this homogeneity condition can be expressed as a variational problem. An analytical solution is presented for this variation problem. This solution describes the optimal field shape (OFS) to obtain the best possible homogeneity for a given magnet length. In practice the ideal shape can be obtained by superposing a series of solenoids of different lengths but the homogeneity is generally not good enough so that in-beam correction coils are needed that include corrections for the line integral differences caused by the finite-beam divergence. The solution is presented together with a method to implement it in practice using discrete in-beam current distributions. The resulting magnet has a homogeneity of 10-6, so that the Larmor precession angle is still well defined after 104 turns.