I am working on a code where I perform dot and cross product operations on a large list of vectors multiple times. I am using MapThread to achieve this but I feel the speed of operation is not up to the mark.
The operation I want to achieve is this, $f(\mathbf{S}_1,\mathbf{S}_2)=\frac{1}{a^2+b^2+c^2(1-(\mathbf{S}_1.\mathbf{S}_2)^2)+2 a b \mathbf{S}_1.\mathbf{S}_2}(a \mathbf{S}_1+b \mathbf{S}_2-c (\mathbf{S}_1 \times \mathbf{S}_2), a \mathbf{S}_2+b \mathbf{S}_1+c (\mathbf{S}_1 \times \mathbf{S}_2))$.
$\mathbf{S}_1$ and $\mathbf{S}_2$ are three dimensional vectors on the unit sphere and $a,b,c$ are arbitrary. What I need to compute is $f(\mathbf{\tilde{S}}_{2n-1},\mathbf{\tilde{S}}_{2n}), \hspace{0.2in} n=1...L/2$ where $\mathbf{\tilde{S}}$ is a list of normalized $3D$ vectors of length $L$.
Here is the sample code I have now,
N1=1000;
r1 = ArcCos[RandomReal[{-1, 1}, N1]];
r2 = RandomReal[{0, 2*Pi}, N1]; a=2;b=3;c=4;
spinsinit = Transpose[{Sin[r1]*Cos[r2], Sin[r1]*Sin[r2], Cos[r1]}]; spins = spinsinit; \[Tau] = 1;
qq1 = Table[list1 = spins[[2*Range[N1/2] - 1]]; list2 = spins[[2*Range[N1/2]]]; list3 = MapThread[Dot, {list1, list2}]; list31 = MapThread[Cross, {list1, list2}]; list32=Sqrt[a^2+b^2+c^2 (1-list3^2)+2 a b list3
]; list4 = (a list1 + b list2 + c list31)/(list32); list5 = (a list2 + b list1 - c list31)/(list32);spins = Normalize /@ Flatten[Transpose[Join[{list4, list5}]], 1],{i,1,100}];
In context to this code, I have two questions.
It seems I have to renormalize the vectors after some iterations because somehow numerical errors creep in and the results blow up, is there anyway more efficient way to tackle this phenomena?
I don't think this code is fully optimized, the sample code takes $\sim 1-2$ seconds to run, and I need to repeat this operation for around $10^6$ times at least, it just does not seem feasible. So any improvements will be greatly appreciated.
list32
, since its purpose is to renormalize the result. (2) Look intoParallelTable
, which may save you some time. $\endgroup$