I am trying to get solution to an equation in a loop. The isolate equation works

rb = 2;
ri[x_] := FindRoot[y - ArcTan[y] - x == 0, {y, 0.01}]
srb = y /. %
s = srb/rb
rinv = (s^2 + rb^2)^(1/2)

However, when I try to do it repeatedly with a While, Do or any other command, I do not get a solution for y. Any clues?

rb = 2;
ri[x_] := (FindRoot[Tan[y] - y - x == 0, {y, 0.01}];
  srb := y /. %;
  s := srb/rb;
  rinv := (s^2 + rb^2)^(1/2))
i = 0.001;
While[i < 0.004, ri[i]; Print["i ", i]; Print["s ", s]; 
  i = i + 0.001];


  • $\begingroup$ Hi and welcome to Mma.SE! Please take the time to format your questions. It makes it easier to read for the folks who might be able to answer your question. Above the edit window is a help ? button. Formatting code blocks can be done by indenting four spaces or using the {} button; inline code is formatted between back-ticks. You can examine the edit I made to see what I changed. $\endgroup$ – Michael E2 May 4 '14 at 17:20

You're relying on % to capture the result of FindRoot in the loop, which won't work because % is shorthand for the last output expression from the Mathematica evaluator, i.e. 0.001 (from the Set expression for i just prior to your loop expression).

You should make sure you properly capture the result of FindRoot in a variable before you use it in a later sub-expression. For example:

rb = 2;

ri[x_] :=
 Block[{root, y},
  root = FindRoot[Tan[y] - y - x == 0, {y, 0.01}];
  srb = y /. root;
  s = srb/rb;
  rinv = (s^2 + rb^2)^(1/2)

i = 0.001;

While[i < 0.004,
 Print["i ", i];
 Print["s ", s];
 i = i + 0.001

(Note that I've also adjusted your use of SetDelayed (:=) to Set (=), since there doesn't seem to be any purpose in this specific example to delay evaluation of those intermediate calculations.)

| improve this answer | |
  • $\begingroup$ This is my first time in the system, and I'm not going to follow the recommendations: thank you for solving my problem so easily... I'll try to come up with an intelligent follow up, but for the moment your answer did the trick for me $\endgroup$ – Horacio Ahuett May 5 '14 at 1:33
  • $\begingroup$ @HoracioAhuett Since your problem was solved months ago you should accept billisphere's answer by clicking the check-mark symbol. $\endgroup$ – eldo Jul 3 '14 at 21:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.