Message Boards Message Boards

0
|
3475 Views
|
1 Reply
|
0 Total Likes
View groups...
Share
Share this post:

Why does this Manipulate command fail to stop/converge?

Posted 11 years ago
I'm writing a program in Mathematica that will demonstrate the bisection method for finding the root of a function. The Manipulate command below does not stop updating for some reason and the value displayed goes to 0. Why is this happening?
 In[1]:= g[x_] := x^3 - 9 x + 3
 In[2]:= a = FindInstance[g[x] > 0, x][[All, 1, 2]][[1]]
 In[3]:= b = FindInstance[g[x] < 0, x][[All, 1, 2]][[1]]
 
 In[6]:= Manipulate[
 
      Module[{c}, c = Mean[{a, b}];
 
      For[i = 0, i < k, i++, c = Mean[{a, b}]; a = If[g[c] > 0, c, a];

        b = If[g[c] < 0, c, b]]; N[g[c]]], {k, 1, 10, 1}]
POSTED BY: Tyler O'Neill
Becuase you had symbols in Manipulate expression (a,b)  that were changing, and Manipulate was tracking them by default. There are many way to solve this, here is one way (make everything needed local a private module inside Manipulate)
 Manipulate[
 Module[{c, i, a, b, g, x},
   g[x_] := x^3 - 9 x + 3;
   a = FindInstance[g[x] > 0, x][[All, 1, 2]][[1]];
   b = FindInstance[g[x] < 0, x][[All, 1, 2]][[1]];
   c = Mean[{a, b}];
   For[i = 0, i < k, i++,
  
    c = Mean[{a, b}];
   a = If[g[c] > 0, c, a];
   b = If[g[c] < 0, c, b]
   ];
  N[g[c]]
  ],
{{k, 1, "k="}, 1, 10, 1, Appearance -> "Labeled",ContinuousAction -> False}
]
Another way, if you want to keep some things global, is to add an explicit Tracking option so that Manipulate knows what to track. It will now track `k` only. But it is not good idea to put things in global context and then reference global variables from inside a Module.
 g[x_] := x^3 - 9 x + 3;
 a = FindInstance[g[x] > 0, x][[All, 1, 2]][[1]];
 b = FindInstance[g[x] < 0, x][[All, 1, 2]][[1]];
 Manipulate[
 Module[{c, i},
   c = Mean[{a, b}];
   For[i = 0, i < k, i++,
    c = Mean[{a, b}];
    a = If[g[c] > 0, c, a];
   b = If[g[c] < 0, c, b]
   ];
  N[g[c]]
  ],
{{k, 1, "k="}, 1, 10, 1, Appearance -> "Labeled",ContinuousAction -> False},
TrackedSymbols :> {k}
]
POSTED BY: Nasser M. Abbasi
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