Re: while loop - numerics
- To: mathgroup at smc.vnet.net
- Subject: [mg119003] Re: while loop - numerics
- From: Peter Pein <petsie at dordos.net>
- Date: Thu, 19 May 2011 07:43:30 -0400 (EDT)
- References: <ir09se$23j$1@smc.vnet.net>
Am 18.05.2011 13:17, schrieb Anna Kaladze: > Hi all, > > > > I am new in loop writing in Mathematica, so your help on the following > seemingly simple problem would be appreciated. I have the following > commands: > > ------------------------------------------------- > > tol=1/100; > > > > DM=9; > > > > yguess=0.5; > > > > x=yguess^2 > > 0.25 > > > > yfeedback=x*yguess > > 0.125 > > > > Error=Abs[yfeedback-yguess] > > 0.375 > ------------------------------------------- > Without doing any equations solving/substitutions or any algebraic > manipulations, or utilizing Table commands, I need to have a while loop > command applied to the above code, such that for a given yguess value > entered (now it is set to 0.5 for the first iteration), Mathematica would > calculate yfeedback and the Error, every time updating yguess with the > following rule: yguess = the last calculated value of yguess*(1+last > calculated value of Error/DM), until Error in the last iteration is less or > equal tol. And then report what that yguess value is. > > For yguess = 0.5, we obviously get after 1st iteration that yfeedback=0.125 > and a large resulting Error value 0.375. So, the yguess needs to be updated > as 0.5*(1+0.375/DM), and that would become 0.520833. Now in the second > iteration yguess takes the value of 0.520833, and then the resulting Error > would become 0.379548, and then the updated yguess would become > 0.520833*(1+0.379548/DM)= 0.542798 and so on until the stopping criteria is > achieved. (Somewhere when the program calculates yguess close to unity the > program should stop obviously). The question is how to write such a code. > > Thanks in advance. > > Anna Hi Anna, this is a typical problem for "NestWhile[..]". The following function will return the pair {yguess, error} when the termination condition is satisfied. I built it with two emergency brakes; one restricts the number of iterations to 10000 and the other breaks when the error becomes greater than 10^10 (iteration diverges): iterate[yguess_]:= Block[{tol = 1/100, DM = 9, tmp}, NestWhile[{tmp = #[[1]](1 + #[[2]]/DM), Abs[tmp(tmp^2 - 1)]} &, {yguess, Abs[yguess(yguess^2 - 1)]}, 10^10 > #[[2]] > tol &,1,10000] ] if you use "NestWhileList" in place of "NestWhile", you'll get a list of all calculated {guess, error} - pairs. hth, Peter