There's luck involved too. In the limiting case, imagine you have 0.001% of the network hash rate and need a 1 block lead. This can happen every now and then, but getting a 2 block lead is basically impossible.
The exact formula is given in the Bitcoin whitepaper <https://bitcoin.org/bitcoin.pdf>, see page 6 and on.