Post Reply 
All decimal digits of reals in CAS
04-22-2015, 03:33 AM (This post was last modified: 04-22-2015 03:33 AM by Joe Horn.)
Post: #7
RE: "dec": All decimal digits of reals in CAS
(04-20-2015 02:54 PM)compsystems Wrote:  Please Joe Horn can comment on each line of code DEC() to understand the logic of the algorithm

thanks

See listing below. The explanations are below their respective lines of code. "Pathological input" means reals so close to integers that some CAS functions fail to distinguish between them and the neighboring integer.

Basic concept: Multiply by 10, chop off the integer part, and repeat, until input goes to zero.

Input --> Output string at each iteration
3.1416 --> "3."
1.416 --> "3.1"
4.16 --> "3.14"
1.6 --> "3.141"
6 --> "3.1416"
0 --> Exit

Code:
#cas
dec(x):=BEGIN
 LOCAL p,s,f;
// p = input's XPON (Power of 10)
// s = output String
// f = sign of input
  IF x = 0 THEN RETURN("0");  END ;
// bugfix: handle input of 0
  f:=Sign(x);
// Sign (not SIGN or sign) for pathological inputs (e.g. 0.5-0.4-0.1)
  x:=abs(x);
// force input to be positive to simplify code;
// restore sign before exiting if input was negative
  p:=XPON(x);
  x/=10^p;
// similar to x:=MANT(x) but more accurate for pathological inputs
  IF IP(x)=0 THEN p--; x*=10; END;
// bugfix: lets inputs like 0.1 work correctly
  s:=STRING(IP(x))+".";
// seed output with integer part and decimal point 
  x:=FP(x);
// remove integer part and begin main loop 
  WHILE (x>0) AND ((SIZE(s))<1000) DO
// stop if input is exhausted or Prime is bored
    x*=10;
// shift next digit to the left of the decimal point
    s+=STRING(IP(x));
// append next digit to the output string
    x:=FP(x);
// discard that digit and repeat loop
   END;;
  IF f<0 THEN s:="-"+s;  END ;
// retore negative sign if input was negative
  IF p>0 THEN s:=s+"E+"+STRING(p);  END ;
  IF p<0 THEN s:=s+"E-"+STRING(abs(p));  END ;
// if there was an exponent, append it
  RETURN(s);
END;
#end

<0|ΙΈ|0>
-Joe-
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread



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