Re: Continued Fractions

*To*: mathgroup at smc.vnet.net*Subject*: [mg75104] Re: Continued Fractions*From*: "Christopher J. Henrich" <chenrich at monmouth.com>*Date*: Mon, 16 Apr 2007 20:24:46 -0400 (EDT)*References*: <evvbni$b5u$1@smc.vnet.net>

In article <evvbni$b5u$1 at smc.vnet.net>, Wu Weidong <ghcgwgwg at singnet.com.sg> wrote: > Hi, > I'm working on a function which takes 2 integer values as input, a and b an= > d outputs a list of integers corresponding to the continued fraction repres= > entation of the rational number a/b. > > My function is as follows: > > build[a_Integer,b_Integer, l_List] :== Module[{r==1,q,temp}, > While[r!==0, > If[a>==b, > q==Quotient[a,b]; > l==Append[l,q]; > r == a-b*q; > a == r, > > temp == a; > a == b; > b == temp; > ]; > ]; > l > ]; > > Essentially, if the fraction given is less than 1, the first number in the = > list is 0. The function then proceeds to find the quotient of the numerator= > and denominator (and add that to the list) and the remainder. If the remai= > nder is less than one, it takes the reciprocal and splits it into a whole-n= > umber part plus another fraction which will be less than 1 and repeat. It s= > tops when the remainder is 0. > > When I tried to run the program, I get the following error messages: > > Set::shape: Lists {} and {2} are not the same shape. > > Set::setraw: Cannot assign to raw object 45. > > Set::shape: Lists {} and {2} are not the same shape. > > Set::setraw: Cannot assign to raw object 45. > > Set::shape: Lists {} and {2} are not the same shape. > > General::stop: Further output of Set::shape > will be suppressed during this calculation. > > Set::setraw: Cannot assign to raw object 45. > > General::stop: Further output of Set::setraw > will be suppressed during this calculation. > > > However, if I just run the While part of the function with a==45, b==16, l= > =={}, r==1 (so I can enter the while loop), I can find the right result (2,= > 1,4,3), so I believe my algorithm should be correct. The errors only appear= > when I put the while loop under the Module structure. > > What is wrong with my program? > First, in transcribing your code you doubled many equals signs, making it syntactically incorrect. But the real problem is that Mathematica passes arguments by vale. If you try to evaluate build[45,17], then when the Mathematica interpreter sees the statement "a = r", it tries to execute "45 = 1", aassuming that r has the value 1 at this point. Thus the error message about "taw object 45." If you want to code in this style, you need to define local variables within the Module expression, and initialize them with the values of "a" and "b". -- Chris Henrich http://www.mathinteract.com God just doesn't fit inside a single religion.