• Remix
  • Share
  • New Entry

on 26 Oct 2022
  • 2
  • 44
  • 0
  • 1
  • 280
% Calculate N digits of pi without sym or vpa via spigot algorithm and
% visualize result as an indexed color image.
%
% Algorithm based on:
% S. Rabinowitz and S. Wagon, "A spigot algorithm for the digits of pi,"
% American Mathematical Monthly, 102(3):195-203, Mar 1995.
% http://maa.org/sites/default/files/pdf/pubs/amm_supplements/Monthly_Reference_12.pdf
%
% Note that a few obfuscations and tricks are employed to minimize
% character count.
n=30; % Dimension of output image
N=n^2; % Number of digits of pi
t=10; % Save characters
f=@floor; % Save characters
m=f(t*N/3); % Length of A
A=2*ones(1,m); % Initialize coefficients A
z=0; % Nines counter
d=0; % Pre-digit
p=eye(n); % Pre-allocate n-by-n matrix to store digits of pi
i=0; % Digits counter
% Use while-loop to ensure at least N digits are obtained
while i<N
% Regularize A array
q=0;
for j=m:-1:1
x=t*A(j)+q*j;
k=2*j-1;
A(j)=mod(x,k);
q=f(x/k);
end
A(1)=mod(q,t);
q=f(q/t);
if q==9
z=z+1; % Increment counter if pre-digit is nine
else
v=q<t;
p(i(i>0&i<=N))=d+~v;% Write digit if q<10, otherwise digit+1
i=i+1;
for j=1:z
p(i(i<=N))=9*v; % Write 9 if q<10, otherwise 0
i=i+1;
end
d=q*v; % Update pre-digit
z=0; % Reset nines counter
end
end
p(i(i<=N))=d; % Append last digit if necessary
% Display image of digits of pi row-wise, apply colormap
% 0=black; 1=navy blue; 2=blue; 3=gray blue; 4=cyan;
% 5=blue green; 6=bright green; 7=yellow; 8=orange; 9=red
% Note 6 consecutive nines (red) near bottom
imshow(p'+1,[0 0 0;jet(t-1)]);
% Uncomment below to display digits (exceeds length limt):
%set(colorbar,'Ticks',1.5:10.5,'TickLabels',('0':'9')','TickD','n');
%[x,y]=ndgrid(1:n);
%text(x(:),y(:),num2str(p(:)),'FontSi',8,'Col','w');
Remix Tree