I'm using Expectation
to calculate the Gaussian integral of a user-supplied function. The following works well and fast (< 1 second):
a[xi_, xj_] := E^(-1/2*(xi - xj)^2/σa^2);
Expectation[a[x[i], x[j]], x[i] \[Distributed] NormalDistribution[xav[i], σ[i]]]
If I try it on an indefinite Sum
, it takes 165 seconds to ultimately fail:
Expectation[
Sum[a[x[i], x[j]], {j, n}, Method -> "Procedural"],
x[i] \[Distributed] NormalDistribution[xav[i], σ[i]]
]
Manually switching the order to a Sum
of the Expectation
works great (again, < 1 sec):
Sum[
Expectation[a[x[i], x[j]], x[i] \[Distributed] NormalDistribution[xav[i], σ[i]]],
{j, n}, Method -> "Procedural"
]
However, all this is happening inside another function that takes arbitrary input (including the Sum
), so I want to switch the Sum
and Expectation
automatically. The following replacement rule does the trick, but is very slow (165 seconds):
Expectation[
Sum[a[x[i], x[j]], {j, n}, Method -> "Procedural"],
x[i] \[Distributed] NormalDistribution[xav[i], σ[i]]
] /. Expectation[Sum[func_, range_, opts___], dist_] :> Sum[Expectation[func, dist], range, opts]
Is there a better (faster, more elegant) way to achieve the same output?
x[i]
is a random variable, then isn'tx[j]
also a random variable? If so, the distribution ofx[j]
seems to be ignored. Also, because the sum overj
includesi
, the case ofa[x[i],x[i]]
occurs. The value ofExpectation[a[x[i], x[i]], x[i] \[Distributed] NormalDistribution[xav[i], \[Sigma][i]]]
becomes 1 which is not the general form that you show. Am I missing something? $\endgroup$x[j]
that are distributed not thex[i]
). The problem still exists, but I'll need to put theExpectation
s inside theSum
earlier, so maybe not relevant to me anymore. $\endgroup$x[i]
andx[j]
are the traits of interacting individuals, who compete with competition kernela[x[i], x[j]]
. Assuming each species' traits are normally distributed, we have to integrate over their distributions to compute competition. See this paper for more info. $\endgroup$