### Complex.BC - Rudimentary complex number handling for GNU BC ## Not to be regarded as suitable for any purpose ## Not guaranteed to return correct answers # Read a digit from the decimal representation of a number # read_digit(3210.987, -1) returns 9 as that is the digit in # the 10^-1 position. define read_digit(number, place) { auto os,d;os = scale number*=10^-place scale=0 d = (number%10)/1 scale=os return(d) } # MakeComplex: Turn two numbers into one by interleaving the digits define makecomplex(r,i) { auto c, rd, id, ri, ii, j, sign r /= 1 i /= 1 ri = length(r)-scale ii = length(i)-scale sign = 1 if (r<0){r*=-1;sign+=2} if (i<0){i*=-1;sign+=1} if(ri=0){ return(makecomplex(sqrt(r),0)) } else { return(makecomplex(0,sqrt(-r))) }} sr = sqrt((sqrt(r^2+i^2)+r)/2) si = i/sr/2 return makecomplex(sr,si) } # subfunctions for use by cintpow define mod(n,m) {auto s;s=scale;scale=0;n%=m;scale=s;return(n)} define int(n) {auto s;s=scale;scale=0;n/=1;scale=s;return(n)} # Raise a complex number [c] to an integer power [n] # NB: n is a standard bc number and not a complex define cintpow(c, n) { auto x x = makecomplex(1,0) n = int(n) if(n<0)return( cdiv(x,cintpow(c,-n)) ) if(n==0)return( x ) if(n==1)return( c ) if(n==2)return( csquare(c) ) while(n) { if(mod(n,2)) { x = cmul(x, c) ; n -= 1 #print "DEBUG: cintpow - odd_ (",n,")\n" } else { c = csquare(c) ; n = int(n/2) #print "DEBUG: cintpow - even (",n,")\n" } } return x }