Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
1995
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 1995

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Re: ReadDigits

  • To: mathgroup at christensen.cybernetics.net
  • Subject: [mg1812] Re: [mg1760] Re: ReadDigits
  • From: Allan Hayes <hay at haystack.demon.co.uk>
  • Date: Mon, 31 Jul 1995 23:09:29 -0400

In article <3ui5a6$231 at news0.cybernetics.net>, insshc at gsusgi2.gsu.edu
(Samuel H. Cox) wrote:

> The function RealDigits[x, b] returns a list of two items.  For  
example,
> RealDigits[Pi //N]
> {{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3}, 1}
>
> What is the inverse of this function?  That is, given the base b, a 
> list {...} of base b digits, and an interger n, how do we  
elegantly obtain x for which RealDigits[x, b] = {{...},n}?


In  [mg1760] Massimo Cafaro <m.cafaro at agora.stm.it>
responded:

>The code below solve the problem. It can be improved to gain
> elegance.
>
> Inv[b_,list_,n_]:=
>	Module[{d,nber,x},
> 		d=Dimensions[list][[1]];
> 		nber=0;
> 		Do[x=list[[i]];nber=N[nber+x*10^(n-i),d],{i,d}];
>       	Print[nber]
>       ];

Here is a variant of this code, where {r,n} is RealDigits[x,b] for  
the real number x that we want to recover.

Inv2[{r_,n_}, b_:10]:=
   Module[{nber,d},
      d = Length[r];
      nber=0;
      Do[nber= nber+r[[i]]*10^(n-i),{i,d}]; (*exact arithmetic*)
      N[nber,d] (*output the answer*)
   ];

(it also uses the n automatically)

A more functional form is

Inv3[{r_,n_},b_:10] := N[(b^(n-Range[#])).r, #]&[Length[r]];

Comparison:

rd = RealDigits[N[Pi]]
	{{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3}, 1}

Inv2[rd]//Timing
	{0.05 Second, 3.141592653589793}
Inv3[rd]//Timing
	{0.0166667 Second, 3.141592653589793}
	
Problem:

A problem arises when b is not 10: for example,when b is 2, we can  
get too many digits

N[Pi]
	3.141592653589793

rd2 = RealDigits[%, 2];

Inv3[rd2,2]
	3.14159265358979311599796346854418516159057617187500000

Adjustment:

The following adjustment nearly corrects this

Inv4[{r_,n_},b_:10] :=
   N[
      (b^(n-Range[#])).r,
      Ceiling[#] N[Log[b]/Log[10]]
   ]&[Length[r]];

Inv4[rd2,2]
	3.141592653589793

But not quite:

N[Pi,30]
	3.14159265358979323846264338328

rd3 =  RealDigits[%, 2];

Inv4[rd3,2]
	3.141592653589793238462643383279

Allan Hayes
De Montfort University Leicester
hay at haystack.demon.co.uk





  • Prev by Date: Re: Bugs with transcendental functions?
  • Next by Date: Gibbs Sampling in Mathematica?
  • Previous by thread: Re: Exponetial Fit
  • Next by thread: Gibbs Sampling in Mathematica?