array solution to iteration/recursion? problem?

0. I assume that dt is initialized somewhere.

I just arbitrarily assign it to 0.34.

1. The C program as stated actually overwrites

the ends of t,x,v (index errors if C were to check

index bounds). I just arbitrarily do one less iteration.

2. t is clearly just dt*i.n

3. A straightforward translation of the C program gives

the following:

dt =: 0.34

ft =: 12.566

NB. Recursion for position and velocity

foo=: 3 : 0

t=: y.$ 0

x=: y.$ 0

v=: y.{.1

for_i. i. y.-1 do.

t=: (dt*1+i) (1+i)}t

x=: ((i{x)+ft*i{v) (1+i)}x

v=: ((i{v)-ft*i{x) (1+i)}v

end.

''

)

foo 10

x ,. v

0 1

12.566 1

25.132 _156.904

_1946.53 _472.713

_7886.64 23987.4

293539 123091

1.8403e6 _3.56551e6

_4.2964e7 _2.66907e7

_3.78359e8 5.13194e8

6.07044e9 5.26766e9

4. The key to removing the explicit looping, is to treat successive

elements of x and v as 2-element vectors, rather than elements

in separate vectors. Then the recursion:

x[i+1] = x[i] + v[i] * ft; /* trouble line 1 */

v[i+1] = v[i] - x[i] * ft; /* trouble line 2 */

can be written as the matrix equation:

[x(i+1)] = [1 ft] [x(i)]

[v(i+1)] [-ft 1] [v(i)]

Now it is easy to see a non-looping J solution:

M=: 2 2$1,ft,(-ft),1

M&(+/ .*)^:(i.10) 0 1

0 1

12.566 1

25.132 _156.904

_1946.53 _472.713

_7886.64 23987.4

293539 123091

1.8403e6 _3.56551e6

_4.2964e7 _2.66907e7

_3.78359e8 5.13194e8

6.07044e9 5.26766e9

Quote:

----- Original Message -----

Sent: Thursday, November 01, 2001 14:35 PM

Subject: array solution to iteration/recursion? problem?

> I saw this chunk of C code in a book I want to find an array solution

> for (as practice in array thinking since I am a beginner).

> /* <---- C code starts here ----> */

> #define NMAX 10001

> #define MMAX 500

> double t[NMAX], x[NMAX], v[NMAX];

> t[0] = x[0] = 0.0; v[0] = 1.0;

> ft = 12.566;

> /* Recursion for position and velocity */

> for (i = 0; i < NMAX; i++)

> {

> t[i+1] = dt * (i+1);

> x[i+1] = x[i] + v[i] * ft; /* trouble line 1 */

> v[i+1] = v[i] - x[i] * ft; /* trouble line 2 */

> if ((i+MMAX) % MMAX == 0)

> printf("%16.8f %16.8f %16.8f\n", t[i], x[i], v[i]);

> }

> }

> /* <----- C code ends here --------> */

> So far, I have been able to translate everything into j (in terms of

> arrays, including the 'if' part and the t[i+1] part ) except for the

> x[i+1] = x[i] + v[i] * ft;

> v[i+1] = v[i] - x[i] * ft;

> part.

> My questions are:

> a. What will a pure array based solution in j look like for

> x[i+1] = x[i] + v[i] * ft;

> v[i+1] = v[i] - x[i] * ft;

> b. Are control structures unavoidable for this problem?

> I suspect nested arrays might be involved but I don't know.

> I am a novice novice novice j learner so please don't flame me.

> Gilbert