2
$\begingroup$

Just for fun, I'm trying to write up some code that will list a finite number of the digits of pi, i.e. {3,1,4,1,5,...,#}. I have the general pattern, but for some reason it's not being implemented properly in my For loop.

For[n = 2, n <= 10, n++,
    p = Pi;
    int[x_] = IntegerPart[x];
    digit = Table[0, {m, 1, 10}];
    tab[[1]] = int[p];
    tab[[n]] = int[10^(n - 1) (p - Sum[10^(-k) tab[[k + 1]], {k, 0, n - 2}])];
 ]

This generates the list

{3, 0, 0, 0, 0, 0, 0, 0, 0, 141592653}

I've tried checking the nth term rule like this:

t1 = 3; t2 = 1; t3 = 4; t4 = 1; t5 = 5;
int[p]
int[10 (p - t1)]
int[100 (p - t1 - t2/10)]
int[1000 (p - t1 - t2/10 - t3/100)]
int[10000 (p - t1 - t2/10 - t3/100 - t4/1000)]
int[100000 (p - t1 - t2/10 - t3/100 - t4/1000 - t5/10000)]

which works, giving 3, 1, 4, 1, and 5, as expected.

Note: I'm sure there's a much more efficient way of doing it, but I'm hardly a programmer - I'm not necessarily looking for suggestions to make it less expensive or anything, just why the heck this isn't working. -_-

$\endgroup$
  • 3
    $\begingroup$ In any event, look up RealDigits[]. $\endgroup$ – J. M. is away Aug 27 '15 at 2:17
  • $\begingroup$ I should have expected a function like that to exist. Thanks for the heads up. $\endgroup$ – user170231 Aug 27 '15 at 2:18
  • 1
    $\begingroup$ Anyway: all those exponentiations are expensive. So: lob off the integer part, multiply the fractional part by 10, lather, rinse, repeat. $\endgroup$ – J. M. is away Aug 27 '15 at 2:22
  • 1
    $\begingroup$ For nth fractional digit of Pi, you can simply evaluate RealDigits[Pi, 10, 1, -n][[1, 1]]. $\endgroup$ – kirma Aug 27 '15 at 12:13
5
$\begingroup$

What's wrong with your code is that the summation is done over incorrect indices. It should be as follows.

p = Pi;
int[x_] := IntegerPart[x]

With[{m = 10},
  tab = Table[0, {n, 1, m}];
  tab[[1]] = int[p];
  For[n = 2, n <= m, n++,
    tab[[n]] = int[10^(n - 1) (p - Sum[10^(1 - k) tab[[k]], {k, n - 1}])]];
  tab]
{3, 1, 4, 1, 5, 9, 2, 6, 5, 3}

My revisions also make a few improvements to your code for the sake of efficiency, but the code is still horribly inefficient.

$\endgroup$
4
$\begingroup$

As I noted, you really want to use RealDigits[] for this. Still, if you want to do a loop:

f = N[π, 20]; b = 10;
Table[i = IntegerPart[f];
         f -= i; f *= b; i,
         {20}]

should yield a pile of $\pi$ digits. Change b to some other integer bigger than $3$ to see base-b digits.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.