Message Boards Message Boards

0
|
8034 Views
|
5 Replies
|
0 Total Likes
View groups...
Share
Share this post:

unintended recursion

Posted 9 years ago

/Users/bruceackerson/Desktop/UpdateVariable.tiff

I understand getting recursion when the Vx variable is on the rhs and lhs. But what do I do, for the recursion in the image?

In case the image doesn't show

Clear[S1, Vx, [Delta], [CapitalSigma]yyMinusP];

S1 = Vx[i1, j1];

Vx[i1, j1] = S1 + [Delta]/2 + [CapitalSigma]yyMinusP/2;

$RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>

POSTED BY: Bruce Ackerson
5 Replies

As you have it written, S1 needs Vx, which, in turn needs S1, etc. Thus an endless loop. You might try indexing the variables S[i], Vx[i,j], which would enable finite loops.

POSTED BY: S M Blinder

The definition of S1 depends on Vx[i1, j1] and the definition of Vx[i1, j1] depends on S.

A simplified example would be:

a = b
b = a + 2

This is how the evaluator thinks about this.

a = b
(* Every instance of the symbol a will now be replaced by the symbol b *)

b = a + 2
(* Oh look! It's the symbol a. Better replace it with b *)

b = b + 2
( * All instances of b should be replaced with b + 2 *)

(* Oh look! it's the symbol b. Better replace it with b+2 *)
b = b + 2 + 2

(* Oh look! it's the symbol b. Better replace it with b+2 *)
b = b + 2 + 2 + 2

(* Oh look! it's the symbol b. Better replace it with b+2 *)
b = b + 2 + 2 + 2 + 2

.....
POSTED BY: Sean Clarke

Has something changed in Mathematica? I looked back at older programs.

S[i] = S[i] + 1

Updated S[i] without recursion. Now it does, even inside a For loop. If I can't do this without recursion, how does one update a variable to plug back into a function?

POSTED BY: Bruce Ackerson

No. This hasn't changed. It would be a really drastic change to the language.

This is a counterintuitive thing for people people. It's commonly stumbled over. In other languages that aren't based on symbolic manipulation, you wouldn't see this problem, but an error message instead.

If you run (a = a + 1) in a fresh kernel (without definitions) you'll see that it goes on an infinite loop. The key is that you need to define to a before you can make changes to it. So you should run something like

a = 0;
a = a + 1;

In most other programming languages, you would get an error message if you tried to increment a without first giving it a value. That doesn't happen in Mathematica because it allows you to work with addition symbolically.

POSTED BY: Sean Clarke

Thanks, I thought I was losing my mind.

POSTED BY: Bruce Ackerson
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract