1

I use Mathematica for calculation of coordinates in format {x[t], y[t]}. For this purpose, I wrote Module TRAJ[x0,y0,tmin,tmax]. When I try to output the results of two calculations with different x0, in a sigle way, like:

TRAJ[5, 460, 200, 202]
{{0.005, 0.38322}, {0.005, 0.382836}, {0.005, 0.382453}}
TRAJ[35, 460, 200, 202]
{{0.035, 0.38322}, {0.035, 0.382836}, {0.035, 0.382453}}

everything is ok, y[t] is same, just x[t] is different. But when I want to output same results in a Table (for further plotting), Mathematica give me "shifted" results without no reason:

Table[TRAJ[g, 460, 200, 202], {g, 5, 35, 30}]
{{{0.005, 0.420867}, {0.005, 0.420671}, {0.005, 0.420475}},
 {{0.035, 0.186067}, {0.035, 0.184697}, {0.035, 0.183327}}}

Now x[t] is different AND y[t] is "shifted".

Is there any way to avoid this wrong Table output? Or I just do something wrong?

d = 50*10^-6;
ρW = 1050;
ρO = 850;
g = 9.81;

μW = 1.002*10^-3;
μO = 7*10^-3;

εO = 2.5*8.854187*10^-12;
εW = 81*8.854187*10^-12;

λ = μW/μO ;

volumeW = N[1/6 Pi*d^3];
m = ρW*volumeW;    

TRAJ[x0_, y0_, tmin_, tmax_] := Module[{},
   ClearAll[ay, vy, vx, yBuoyancy, yDrag, xDrag, xForce, yForce, sol];
   ay[t_] := y''[t];
   vy[t_] := y'[t];
   ax[t_] := x''[t];
   vx[t_] := x'[t];

   yBuoyancy = -(ρW - ρO)*g*volumeW;
   yDrag = 3 Pi*μW*(λ + 2/3)/(λ + 1)*d*(-vy[t]);
   xDrag = 3 Pi*μW*(λ + 2/3)/(λ + 1)*d*(-vx[t]);
   xForce = 0;
   yForce = 0;   
  sol = Flatten[
   NDSolve[{m*ay[t] == yBuoyancy + yDrag + yForce, 
     m*ax[t] == xForce + xDrag, y[0] == y0*0.001, vy[0] == 0, 
     x[0] == x0*0.001, vx[0] == 0}, {x[t], y[t]}, {t, 0, tmax}]];
Table[{x[t], y[t]} /. sol, {t, tmin, tmax }];

Thank you for any advice.

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
4lk4st
  • 43
  • 4

1 Answers1

2

First of all you are using Module wrong. It should start like this:

TRAJ[x0_, y0_, tmin_, tmax_] := 
 Module[{x, y, ay, ax, vy, vx, yBuoyancy, yDrag, xDrag, xForce, yForce, sol},
  ay[t_] := y''[t];
  (* the rest of your code *)

Second, Table works by the mechanism of Block. Refer to What are the use cases for different scoping constructs? and especially WReach's concise example to see how this works. The global value of g is being changed which affects the result of the computation. You instead want only to vary a local value. You can again use Module for that:

Module[{g},
  Table[TRAJ[g, 460, 200, 202], {g, 5, 35, 30}]
]
{{{0.005, 0.38322}, {0.005, 0.382836}, {0.005, 0.382453}},
 {{0.035, 0.38322}, {0.035, 0.382836}, {0.035, 0.382453}}}

Alternatively you could you a construct besides table, e.g. Map:

TRAJ[#, 460, 200, 202] & /@ Range[5, 35, 30]
{{{0.005, 0.38322}, {0.005, 0.382836}, {0.005, 0.382453}},
 {{0.035, 0.38322}, {0.035, 0.382836}, {0.035, 0.382453}}}

While the behavior of Table may come as a shock to you it is actually a valuable aspect of the function and it should not be dismissed as a peculiarity.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371