#!/usr/local/bin/bc -l funcs.bc ### CF.BC - Continued fraction experimentation # run with funcs.bc /* TO DO: rewrite using undocumented array pass by reference to avoid use of global array cf[] */ # sanity check for the below define check_cf_max_() { auto maxarray; maxarray = 4^8;cf_max=int(cf_max) if(1>cf_max||cf_max>maxarray)cf_max=maxarray return 0; } # global var; set to halt output and calculations at a certain point cf_max=0; # Tidy up a newly created cf array # expects the index past the end of the array as a parameter # assumes the last element of large cfs to be invalid due to rounding # and deletes that term. # for apparently infinite (rather than just long) cfs, uses a bc trick # to signify special behaviour to the printcf function. # for apparently finite cfs, checks whether the cf ends ..., n, 1] # which can be simplified further to , n+1] define cf_tidy_(i,p,max) { auto which0; cf[i]=0 if(p>max){ which0=0;if(p=!improper;i--){ temp=n;n=d;d=temp # reciprocal = swap numerator and denominator n+=cf[i]*d } temp=0 if(!improper){temp=n;n=d;d=temp}#correct for having stopped early if(d<0){n*=-1;d*=-1} # denominator always +ve if(!improper&&cf[0]!=0){ print temp=cf[0] if((n<0)==(d<0)){print"+"} # if n and d have same sign... } print n,"/",d return(temp+n/d); } # Convert global array cf[] back into a number define cf2num() { auto n, i; i=check_cf_max_(); if(cf[1]==0)return cf[0]; for(i=1;i=0;i--)n=1/n+cf[i] return(n); } # Convert global array cf[] back into a number ignoring term signs define cf2num_abs() { auto n, i; i=check_cf_max_(); if(cf[1]==0)return cf[0]; for(i=1;i=0;i--)n=1/n+abs(cf[i]) return(n); } # Convert global array cf[] back into a number ignoring term signs # and subtracting one from those absolute values define cf2num_abs1() { auto n, i; i=check_cf_max_(); if(cf[1]==0)return cf[0]; for(i=1;i=0;i--)n=1/n+abs(cf[i])-1 return(n); } # Turn the binary representation of x into a continued fraction-like # structure using global array cf[]. # e.g. 0.1001000011111101110111 -> [0;1,2,1,4,6,1,3,1,3] define bincf(x) { auto i,b,bb,n,j; i=check_cf_max_(); x=abs(x);if(x>1)x=frac(x) x*=2;b=int(x);x-=b;n=1;j=1;cf[0]=0 for(i=0;i 0.11110111101111011110... define cf2bin() { auto n,i,b,x,t; i=check_cf_max_(); #cf[0]=0; x=2^cf[0]-1 b=0;t=1 for(i=1;i