タイミング実験
タイミングの制約を指定しなかったので、素晴らしい統合パッケージで少し実験を行いました。
最適化を行わない場合、立方体の密度が単純な関数である場合、球座標の各積分は標準のラップトップで 0.005 秒で評価できます。
参考までに、Mathematica のプログラムは次のとおりです。
Clear@f;
(* Define a cuboid as density function *)
iP = IntegerPart;
f[{x_, y_, z_}, {lx_, ly_, lz_}] := iP[x - lx] + iP[y - ly] + iP[z - lz] /;
lx <= x <= lx + 3 && ly <= y <= ly + 3 && lz <= z <= lz + 3;
f[{x_, y_, z_}, {lx_, ly_, lz_}] := Break[] /; True;
Timing[Table[s = RandomReal[{0, 3}, 3]; (*sphere center random*)
sphereRadius = Min[Union[s, 3 - s]]; (*max radius inside cuboid *)
NIntegrate[(f[{x, y, z} - s, -s] /. (*integrate in spherical coords *)
{x -> r Cos@th Sin@phi,
y -> r Sin@th Sin@phi,
z -> r Cos@phi}) r^2 Sin@phi,
{r, 0, sphereRadius}, {th, 0, 2 Pi}, {phi, 0, Pi}],
{10000}]][[1]]
結果は、10^4 反復で 52 秒です。
したがって、おそらく多くを最適化する必要はありません...