Re: Re: Code to translate to negative base...
- To: mathgroup at smc.vnet.net
- Subject: [mg64675] Re: [mg64620] Re: Code to translate to negative base...
- From: Richard Palmer <mapsinc at bellatlantic.net>
- Date: Sun, 26 Feb 2006 05:07:57 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
Thanks a lot Valeri, I owe you a drink or a coffee if you ever get to Boston. Richard Palmer On 2/24/06 12:18 AM, "Valeri Astanoff" <astanoff at yahoo.fr> wrote: > Surely not so clever or fast as Paul Abbott's solution, > this my way to handle negative bases with "FindInstance" : > (not thoroughly tested) : > > In[1]:= > myToDigits[k_Integer, base_Integer /; base <= -2]:= > Module[{dd, d, n, fi}, > dd = Table[d[i],{i,0,n = Length[IntegerDigits[k,-base]]+1}]; > fi = FindInstance[k == Sum[d[i]base^i,{i,0,n}]&& > And @@ ((0 <= # <= -base-1)& /@ dd), dd, Integers]; > (dd /. fi // First // Reverse) //. {0,u__} -> {u} > ]; > > myFromDigits[digits:{_Integer..}, base_Integer /; base <= -2]:= > digits.Table[base^i,{i,Length[digits]-1,0,-1}]; > > myToDigits[x_?NumericQ, base_Integer /; base <= -2, > numberOfOutputDigits_Integer /; numberOfOutputDigits >= 1]:= > Module[{y, nid}, > y = Floor[x*(-base)^(2*numberOfOutputDigits)]; > nid = myToDigits[y,base]; > {nid //. {a___,0} -> {a}, Length[nid]-2*numberOfOutputDigits} > ]; > > myFromDigits[{digits:{_Integer..}, > numberOfLeftDigits_Integer /; numberOfLeftDigits >= 1}, > base_Integer /; base <= -2]:= > digits.Table[base^i, {i, numberOfLeftDigits-1, > -(Length[digits] - numberOfLeftDigits),-1}]; > > > Examples : > > In[5]:=myToDigits[123,-10] > > Out[5]={2,8,3} > > > In[6]:= myFromDigits[%,-10] > > Out[6]=123 > > > In[7]:=myToDigits[123.45678,-10,8] > > Out[7]={{2,8,4,6,6,4,8,2},3} > > > In[8]:=myFromDigits[%,-10] > > Out[8]=6172839/50000 > > > In[9]:=N[%,10] > > Out[9]=123.4567800 > > > v.a. >