2

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. -_-

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
user170231
  • 1,611
  • 1
  • 11
  • 17

2 Answers2

5

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.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
4

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.

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574