Post Reply 
Decimal to Fraction Function
08-27-2014, 06:18 PM (This post was last modified: 08-31-2014 02:57 AM by Namir.)
Post: #1
Decimal to Fraction Function
The following function takes the following parameters:

1) x - the fraction to be converted.
2) n - the number of continued fraction terms.
3) toler - the residual tolerance (to prevent divisions by small numbers).

The function returns the following values:

1) The approximation for x.
2) The numerator.
4) The denominator. The approximation for x = numerator / denominator.
4) The difference between x and its approximated value.

Here is the HP Prime listing:

Code:

EXPORT Dec2Frac(x,n,toler)
BEGIN
  LOCAL i,numer,denom,aux,resid,y,m,x0;
  
  x0:=x;
  y:=MAKEMAT(0,n,1);
  // Build continued fraction coefficients
  m:=0;
  FOR i FROM 1 TO n DO
    m:=m+1;
    y(i,1):=IP(x);
    resid:=FP(x);
    IF ABS(resid)<toler THEN
      BREAK;
    END;
    x:=1/resid;
  END;
  
  // unfold the fractions
  numer:=y(m,1);
  denom:=1;
  FOR i FROM m-1 DOWNTO 1 DO
    aux:=numer;
    numer:=y(i,1)*numer+denom;
    denom:=aux;
  END;
  resid:=x0-numer/denom;
  RETURN {numer/denom,numer,denom,resid};
END;

Here is an example:

Code:
Dec2Frac(pi,4,0.0001)
    {3.14159292035,355,113,0.00000026676}

Enjoy!

Namir

PS: Many many thanks for Joe Horn who patently pointed out the many errors in the code. I feel a bit ashamed, because I should have done a much better job posting these simple programs. My former Jesuit teachers would have commented that I "did a sloppy job!". Thanks Joe!!
Find all posts by this user
Quote this message in a reply
Post Reply 




User(s) browsing this thread: 2 Guest(s)