1 | initial version |
There are (at least) two reasons why your computations get slower when i
increases.
First, in the galtonwatson
function, the while
loops is basically run i
times. For example, you can print i,n
after leaving the while
loop to see this. So of course the bigger i
is, the more computation there will be. But this only explains a linear grow in the time of your computation.
Second, when you write g(mu,n)=(e^-mu * mu^n)/factorial(n)
in the poisson
function, you define a symbolic expression, hence the variable sum
is also a symbolic expression. The size of this expression can (and actually does) grow with your computation. If you add a print sum
in your first function just before returning i-1
, you will see that it starts with small expressions such as 14*e^(-4)
, but when the number i
of loops increases, N
also increases so that poisson()
gets huge entries and has to deal with long symbolic expression, that require more work to be dealt with (comparisons and additions in your case). For example at some point in your computation, the poisson function has to deal with expressions like 2550238050428406819213469230186796710457038334913297649020437009290776623587690225849958231171422547635982429757061594176295874263901615544026377448805360196385122323653063241084162785437552154577478465216934451591637439914252547465299853699560543796189133899256924947210666913788957676219447233148368101219341018550501213846576116206037455500877981155501490135406458094080344650729126/70844983299568090322110112742920523338416993100768511830154325532394931272007563144745759540627587853267356431624585717416519870692624578946059813830541826543646017674726402935877414919947084600537371110174386759651317089097190938443583025355782216979691251401707319246270344592630863189697265625*e^(-204)
and it gets even worse after that.
The same issue appears with rational numbers: they do not have a constant size, so it is likely that iterated computation will lead to rationals with bigger and bigger numerators and denominators. If you want to avoid such explosion of the size of the data that you manipulate, you can work with floating point numbers instead, since those keep constant size along the computation.
sage: a
2550238050428406819213469230186796710457038334913297649020437009290776623587690225849958231171422547635982429757061594176295874263901615544026377448805360196385122323653063241084162785437552154577478465216934451591637439914252547465299853699560543796189133899256924947210666913788957676219447233148368101219341018550501213846576116206037455500877981155501490135406458094080344650729126/70844983299568090322110112742920523338416993100768511830154325532394931272007563144745759540627587853267356431624585717416519870692624578946059813830541826543646017674726402935877414919947084600537371110174386759651317089097190938443583025355782216979691251401707319246270344592630863189697265625*e^(-204)
sage: RDF(a)
0.9124252826570382