0
|
3401 Views
|
|
0 Total Likes
View groups...
Share
GROUPS:

# Why does this Manipulate command fail to stop/converge?

Posted 10 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:= g[x_] := x^3 - 9 x + 3 In:= a = FindInstance[g[x] > 0, x][[All, 1, 2]][] In:= b = FindInstance[g[x] < 0, x][[All, 1, 2]][]  In:= 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}]
 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]][];   b = FindInstance[g[x] < 0, x][[All, 1, 2]][];   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]][]; b = FindInstance[g[x] < 0, x][[All, 1, 2]][]; 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}]