Can I speed up the following plotting code?

I have the following Mathematica code. I do get the output graphs, but it takes like 12 seconds, on my computer. Longer still if I increase the value of n1. Are there ways that can speed up the code?

Code1[A_, n1_] := Module[{E2},
h = 197.327053^2;
a = 0.65;
r0 = 1.285;
k0 = ((V02) 2 m/h)^0.5;
R0 = r0 A^0.333;
m = (A/(A + 1.00866 ))*931.49432;
V02 = 40.5 + 0.13 A;
z = a Sqrt[(2 m/h) (V02 - E2)];
b = a*Sqrt[(2 m/h) (E2)];
q1 = Sqrt[(V02 - E2)/E2];
phi444[E_] := (z R0/a  ) -
Sum[ ArcTan[2 z/n] - 2 ArcTan[z/(n + b)], {n, 1.0, n1}];
t1 = Plot[{Tan[phi444[E2]], -q1}, {E2, 0, 45.0}];
Print[t1]]

• Yes, you can. The slowdown is because you're evaluating the Sum in phi444 at each plot point, but this is unnecessary because it does not depend on the value of E. Instead, change the definition of phi444 to phi444[E_] := (...) - Evaluate@Sum[...] (you can even do away with the function and just make it a constant.
– rm -rf
Commented Jul 10, 2013 at 7:42
• See the second point in this answer and this, for a longer example
– rm -rf
Commented Jul 10, 2013 at 7:47
• hi rm-rf.thanks for your reply. Oops, there is a typo error in my code. Should be phi444[E2_] actually. So parameters b & z in the SUM depend on E2 too. Since they do, is there another way to speed up the output
– raj
Commented Jul 10, 2013 at 8:04
• you may want to correct your question then Commented Jul 10, 2013 at 8:08

The plot goes very quickly if you don't define phi444 as a function, but make it a simple assignment,as you did with z, b and q1. Also, I recommend you localize all the variables you make assignments to in your Module and not just E2.

code1[A_, n1_] :=
Module[{E2, h, a, r0, k0, R0, m, V02, b, q1, phi444},
h = 197.327053^2;
a = 0.65;
r0 = 1.285;
k0 = ((V02) 2 m/h)^0.5;
R0 = r0 A^0.333;
m = (A/(A + 1.00866))*931.49432;
V02 = 40.5 + 0.13 A;
z = a Sqrt[(2 m/h) (V02 - E2)];
b = a*Sqrt[(2 m/h) (E2)];
q1 = Sqrt[(V02 - E2)/E2];
phi444 = (z R0/a) - Sum[ArcTan[2 z/n] - 2 ArcTan[z/(n + b)], {n, 1.0, n1}];
Plot[{Tan[phi444], -q1}, {E2, 0, 45.0}]]

code1[1., 10.]


You might want to try my code:

Code2 = Function[{A, n1}, With[{h = 197.327053^2,
a = 0.65,
r0 = 1.285,
k0 = ((V02) 2 m/h)^0.5,
R0 = r0 A^0.333,
m = (A/(A + 1.00866))*931.49432,
V02 = 40.5 + 0.13 A},
Plot[{Tan[(a Sqrt[(2 m/h) (V02 - E2)] R0/a) -
Sum[ArcTan[2 a Sqrt[(2 m/h) (V02 - E2)]/n] -
2 ArcTan[
a Sqrt[(2 m/h) (V02 - E2)]/(n +
a*Sqrt[(2 m/h) (E2)])], {n, 1.0,
n1}]], -Sqrt[(V02 - E2)/E2]}, {E2, 0, 45.0}]]];


It runs instantly on my machine. (I have some advise on optimization in Mathematica, but it wasn't asked here)

Code2[2, 10]


• You're welcome.
– Ali
Commented Jul 11, 2013 at 8:47