0
$\begingroup$

I have a process that consists of obtaining a data set by scanning 5 variables L, w, d, k, and l using Table. The script follows,

sa = Table[
   If[k == l, 
    Sin[  w (((10^(-8 + L))^2 + (10^(-6 + L)  k - 10^(-6 + L) l )^2)^(
        1/2)) ]/((10^(-8 + L))^2 + (10^(-6 + L) k - 
          10^(-6 + L) l )^2)^2, 
    Cos[d] Sin[
       w (((10^(-8 + L))^2 + (10^(-6 + L)   k + 
              10^(-6 + L) l (Cos[d]))^2 + ((10^(-6 + L) l (Sin[
                 d])))^2 )^2)]/(((10^(-8 + L))^2 + (10^(-6 + L)   k + 
            10^(-6 + L) l (Cos[d]))^2 + ((10^(-6 + L) l (Sin[
               d])))^2 )^2)], {L, 0, 3}, {w, 10, 100, 0.1}, {d, 0, 
    2 \[Pi], \[Pi]/4}, {k, 1, 200}, {l, 1, 200}];

The time taken to complete this process was about 10 hours on an Intel® Core™ i7-6500U (2.50 GHz) processor, 8GB Single Channel DDR3L 1600MHz (1x8GB) memory, and NVIDIA GeForce 930M 4GB DDR3. I wonder if it is possible to reduce the calculation time using For or Do. Thanks in advance

$\endgroup$

1 Answer 1

3
$\begingroup$

You can speed up the calculation considerably by finding numeric solutions instead of exact ones. Moreover, it helps if you avoid branching If statement. If it is still sufficiently, look up Compile, which compiles the function in low level C for even faster execution. You can also evalute the elements of the table in parallel on multiple cores using ParallelTable.

Below is a demonstration of compiling:

test := Table[
   If[k == l, 
    Sin[w (((10^(-8 + L))^2 + (10^(-6 + L) k - 10^(-6 + L) l)^2)^(1/
           2))]/((10^(-8 + L))^2 + (10^(-6 + L) k - 
           10^(-6 + L) l)^2)^2, 
    Cos[d] Sin[
       w (((10^(-8 + L))^2 + (10^(-6 + L) k + 
               10^(-6 + L) l (Cos[d]))^2 + ((10^(-6 + L) l (Sin[
                  d])))^2)^2)]/(((10^(-8 + L))^2 + (10^(-6 + L) k + 
             10^(-6 + L) l (Cos[d]))^2 + ((10^(-6 + L) l (Sin[
                d])))^2)^2)], {L, 0, 3}, {w, 10, 100, 1}, {d, 0, 
    2 \[Pi], \[Pi]}, {k, 1, 10}, {l, 1, 10}];
f = Compile[{L, w, d, k, l}, 
   If[k == l, 
    Sin[w (((10^(-8 + L))^2 + (10^(-6 + L) k - 10^(-6 + L) l)^2)^(1/
           2))]/((10^(-8 + L))^2 + (10^(-6 + L) k - 
           10^(-6 + L) l)^2)^2, 
    Cos[d] Sin[
       w (((10^(-8 + L))^2 + (10^(-6 + L) k + 
               10^(-6 + L) l (Cos[d]))^2 + ((10^(-6 + L) l (Sin[
                  d])))^2)^2)]/(((10^(-8 + L))^2 + (10^(-6 + L) k + 
             10^(-6 + L) l (Cos[d]))^2 + ((10^(-6 + L) l (Sin[
                d])))^2)^2)]];
testN := Table[
   f[N@L, N@w, N@d, N@k, N@l], {L, 0, 3}, {w, 10, 100, 1}, {d, 0, 
    2 \[Pi], \[Pi]}, {k, 1, 10}, {l, 1, 10}];

Testing:

Timing[test] // First
Timing[testN] // First
testN == test
1.98438

0.296875

True
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.