Continued fraction: Difference between revisions

no edit summary
(→‎{{header|Erlang}}: Added Erlang implementation)
No edit summary
Line 726:
' fpi 200 cont.fraction f. cr 3.14159268391981
ok
</pre>
 
=={{header|Fortran}}==
<lang Fortran>module continued_fractions
 
integer, parameter :: long = selected_real_kind(7,99)
 
type continued_fraction
integer :: a0, b1
procedure(series), pointer, nopass :: a, b
end type
 
interface
pure function series (n)
integer, intent(in) :: n
integer :: series
end function
end interface
 
contains
 
pure function define_cf (a0,b1,a,b) result(x)
type(continued_fraction) :: x
integer, intent(in) :: a0, b1
interface
pure integer function a(n)
integer, intent(in) :: n
end function a
pure integer function b(n)
integer, intent(in) :: n
end function b
end interface
x%a0 = a0
x%b1 = b1
x%a => a
x%b => b
end function
 
pure real(kind=long) function output(x,iterations)
type(continued_fraction), intent(in) :: x
integer, intent(in) :: iterations
output = x%a(iterations)
do i = iterations-1,1,-1
output = x%a(i) + (x%b(i+1) / output)
end do
output = x%a0 + (x%b1 / output)
end function output
end module continued_fractions
 
 
program examples
use continued_fractions
 
type(continued_fraction) :: sqr2,pi,napier
 
sqr2 = define_cf(1,1,a_sqr2,b_sqr2)
napier = define_cf(2,1,a_napier,b_napier)
pi = define_cf(3,1,a_pi,b_pi)
 
write (*,*) output(sqr2,10000)
write (*,*) output(napier,10000)
write (*,*) output(pi,10000)
 
contains
 
pure integer function a_sqr2(n)
integer,intent(in) :: n
a_sqr2 = 2
end function
 
pure integer function b_sqr2(n)
integer,intent(in) :: n
b_sqr2 = 1
end function
 
pure integer function a_napier(n)
integer,intent(in) :: n
a_napier = n
end function
 
pure integer function b_napier(n)
integer,intent(in) :: n
b_napier = n-1
end function
 
pure integer function a_pi(n)
integer,intent(in) :: n
a_pi = 6
end function
 
pure integer function b_pi(n)
integer,intent(in) :: n
b_pi = (2*n-1)*(2*n-1)
end function
 
end program examples</lang>
{{out}}
<pre>
1.4142135623730951
2.7182818284590455
3.1415926535895435
</pre>
 
24

edits