We develop a stochastic version of a previously discussed model of optimal herd size selection in ungulates. We assume that a large herd size confers to the animals a high level of protection against predators, but reduces the amount of food which can be eaten by each individual; on the contrary animals belonging to small herds would have access to large amounts of food but would bear a high risk of being killed by predators. Employing a dynamic programming approach we analyze the optimal trade-off between starvation and predation risks under the hypothesis that the animals would try to maximize their expected reproductive fitness during the incoming breeding period. We compare the optimal strategy in environments described by different kinds of stochastic food distributions (including the deterministic limit) for different values of predation pressure and of overall food availability. We obtain general information about the effect of the level of randomness of food distribution on the mean individual fitness and on the number of reproducers (the animals which survive to the beginning of the reproductive season). Moreover we discuss how a certain number of behavioral and ecological processes--which have been often described in natural populations of ungulates and which are usually explained in terms of phenological variations of the ecological landscape--may be interpreted as caused by intrinsic variations of the animals' strategy.