Group Abstract Group Abstract

Message Boards Message Boards

0
|
4.3K Views
|
2 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Avoid error with a Clear[x]?

Posted 10 years ago

hi

x = 1
ClearAll[x]
g[x_] = 1/(1 + x);
Clear[x]
Do[x = g[x], {n, 10}]
x

this leads to an error. i dont understand why. i you can help... is it a sort of bug that needs to restart the kernel or is it a misunderstanding of Mathematica from me ?

POSTED BY: Adrien Guyader
2 Replies
Posted 10 years ago

ok i am used to imperative languages where x has a value, and x=g(x) just calculate g(x) with this value and put it as a new value to x a functional language needs changing the habits your explanation was very clear ok and nest is exactly what i was looking for thanks

POSTED BY: Adrien Guyader
Posted 10 years ago

You can simplify your example even further, if you haven't previously assigned anything to x.

g[x_] = 1/(1 + x);
x = g[x]

or

g[x_] := 1/(1 + x);
x = g[x]

Both of these display the same run-away recursion errors.

You might think about the problem this way. You are assigning something to x. To do that you evaluate g[x]. To do that you look at the right hand side of the definition of g[x] and evaluate everything in that. Doing that means you need the value of x. What is the value of x? You look and see that x is g[x] and the process starts all over again and again and again.

If you think about it, can you then make any sense of this behavior?

While on the surface the notation used in the Mathematica programming language might look similar to other conventional programming languages, below the surface it is anything but this. Really understanding the depths and details of the evaluation process that Mathematica uses may be difficult, but might help explain some of the "more interesting" behaviors that you may run into with continued use.

If what you really want is just the result instead of trying to figure the behavior out then try this instead

g[x_] := 1/(1 + x);
Nest[g, x, 10]

and see if that was what you wanted to accomplish.

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