Arithmetic-geometric mean/Calculate Pi: Difference between revisions

Added solution in Fortran
(Added solution in Fortran)
Line 516:
<pre>
3.141592653589794
</pre>
 
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
{{trans|julia}}
<lang fortran>program CalcPi
implicit none
real(16) :: a,g,s,old_pi,new_pi
real(16) :: a1,g1,s1
integer :: k,k1,i
 
old_pi = 0.0; new_pi = 1.0
a = 1.0; g = 1.0/sqrt(2.0); s = 0.0; k = 0
 
do i=1,100
call approx_pi_step(a,g,s,k,a1,g1,s1,k1)
new_pi = 4 * (a1**2) / (1 - s1)
if (abs(new_pi - old_pi).lt.(2*epsilon(new_pi))) then
! If the difference between the newly and previously
! calculated pi is negligible, stop the calculations
exit
end if
write(*,*) 'Iteration:',k1,' Diff:',abs(new_pi - old_pi),' Pi:',new_pi
old_pi = new_pi
a = a1; g = g1; s = s1; k = k1
end do
 
contains
 
subroutine approx_pi_step(x,y,z,n,a,g,s,k)
real(16), intent(in) :: x,y,z
integer, intent(in) :: n
real(16), intent(out) :: a,g,s
integer, intent(out) :: k
 
a = 0.5 * (x+y)
g = sqrt(x*y)
k = n + 1
s = z + 2**(k+1) * (a**2 - g**2)
end subroutine
end program CalcPi
</lang>
{{out}}
<pre>
Iteration: 1 Diff: 3.18767262223526210594115559912185721 Pi: 3.18767262223526210594115559912185721
Iteration: 2 Diff: 4.59923534892908545980576775287758493E-0002 Pi: 3.14168026874597125134309792159308136
Iteration: 3 Diff: 8.76394187452560419206530659987868041E-0005 Pi: 3.14159262932722599530117726852708257
Iteration: 4 Diff: 3.05653375295980919905749104814626909E-0010 Pi: 3.14159262902157262000519634862133346
Iteration: 5 Diff: 3.71722232047463700728567265969013337E-0021 Pi: 3.14159262902157262000147912630085883
</pre>
 
Anonymous user