This thread explains all, include all the flaws in the current calculation that needs to be fixed. Have a look at that thread.
This is for AoE II HD. Things are a bit different for AoE II DE. The highlights are still true, but the details are a bit different.