Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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}]
ri[0.02151]
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];

Thanks!

share|improve this question
    
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. –  Michael E2 May 4 at 17:20

1 Answer 1

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,
 ri[i];
 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.)

share|improve this answer
    
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 –  Horacio Ahuett May 5 at 1:33
    
@HoracioAhuett Since your problem was solved months ago you should accept billisphere's answer by clicking the check-mark symbol. –  eldo Jul 3 at 21:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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