Arithmetic-geometric mean/Calculate Pi: Difference between revisions

Updated to F2008 and used iso_fortran_env, as real(16) is deprecated
(Updated to F2008 and used iso_fortran_env, as real(16) is deprecated)
Line 519:
 
=={{header|Fortran}}==
{{works with|Fortran|952008 and later}}
{{libheader|iso_fortran_env}}
{{trans|Julia}}
<lang fortran>program CalcPi
! Use real128 numbers: (append '_rf')
use iso_fortran_env, only: rf => real128
implicit none
real(16rf) :: a,g,s,old_pi,new_pi
real(16rf) :: a1,g1,s1
integer :: k,k1,i
 
old_pi = 0.00_rf; new_pi = 1.0
a = 1.00_rf; g = 1.00_rf/sqrt(2.00_rf); s = 0.00_rf; k = 0
 
do i=1,100
call approx_pi_step(a,g,s,k,a1,g1,s1,k1)
new_pi = 4.0_rf * (a1**2.0_rf) / (1.0_rf - s1)
if (abs(new_pi - old_pi).lt.(2.0_rf*epsilon(new_pi))) then
! If the difference between the newly and previously
! calculated pi is negligible, stop the calculations
Line 546 ⟶ 549:
 
subroutine approx_pi_step(x,y,z,n,a,g,s,k)
real(16rf), intent(in) :: x,y,z
integer, intent(in) :: n
real(16rf), intent(out) :: a,g,s
integer, intent(out) :: k
 
a = 0.5 5_rf* (x+y)
g = sqrt(x*y)
k = n + 1
s = z + (2.0_rf)**(real(k)+1.0_rf) * (a**(2.0_rf) - g**(2.0_rf))
end subroutine
end program CalcPi
Line 560 ⟶ 563:
{{out}}
<pre>
Iteration: 1 Diff: 3.1876726222352621059411555991218572118767264271210862720192997052536885 Pi: 3.1876726222352621059411555991218572118767264271210862720192997052536885
Iteration: 2 Diff: 4.59923534892908545980576775287758493E59923494144553332838595459653619370E-0002 Pi: 3.1416802687459712513430979215930813614168029329765329391807042456000691
Iteration: 3 Diff: 8.76394187452560419206530659987868041E76394022067979151556657419559658324E-0005 Pi: 3.1415926293272259953011772685270825714159265389544649600291475881805095
Iteration: 4 Diff: 3.05653375295980919905749104814626909E05653257536554156111405386493810661E-0010 Pi: 3.1415926290215726200051963486213334614159265358979323846636060270664556
Iteration: 5 Diff: 3.71722232047463700728567265969013337E71721942712928151094186846648146566E-0021 Pi: 3.1415926290215726200014791263008588314159265358979323846264338327951628
</pre>
 
Anonymous user