function [P,t,iter] =  agm_pi_compute(d)
%This function compute \pi using the agm iteration.
%initialise timer
tic
%set the variable precision digits to d.
digits(d)
%intialise a to be 1 with d digits of precision
a = vpa(1,d);
%initialise b to 1/\sqrt{2}
b = 1/sqrt(vpa(2,d));
%initialise the sum s to be 1/4
s = 1/vpa(4,d);
p = 1; %set p to be 2^0
%calculate the number of iterations based on the convergence of the method
iter = ceil(log2(d)); 
for k = 1:iter
   c = (a+b)/2; %Calculate arithmetic mean
   b = sqrt(a*b); %calculate geometric mean
   s = s - p*(c-a)^2; %update sum
   p = 2*p; %increase the power of 2
   a = c; %update a to be the arithmetic mean
end
%calculate \pi
P = a^2/s; 
%end timer
t = toc;
end
