Right now you are calculating all trains every 30 ticks, it makes small lags by megafactories.
Can you please change it as not more than one calculation per tick? Such solution makes no UPS lags by megafactories, but the distance calculating will be a little bit not so precise. The same precision will be by #trains = 30.