How to resolve the algorithm Continued fraction step by step in the ATS programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Continued fraction step by step in the ATS programming language
Table of Contents
Problem Statement
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use
a
0
= 1
{\displaystyle a_{0}=1}
then
a
N
= 2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
. For Napier's Constant, use
a
0
= 2
{\displaystyle a_{0}=2}
, then
a
N
= N
{\displaystyle a_{N}=N}
.
b
1
= 1
{\displaystyle b_{1}=1}
then
b
N
= N − 1
{\displaystyle b_{N}=N-1}
. For Pi, use
a
0
= 3
{\displaystyle a_{0}=3}
then
a
N
= 6
{\displaystyle a_{N}=6}
.
b
N
= ( 2 N − 1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Continued fraction step by step in the ATS programming language
Source code in the ats programming language
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)
//
(*
** a coefficient function creates double values from in paramters
*)
typedef coeff_f = int -> double
//
(*
** a continued fraction is described by a record of two coefficent
** functions a and b
*)
typedef frac = @{a= coeff_f, b= coeff_f}
//
(* ****** ****** *)
fun calc
(
f: frac, n: int
) : double = let
//
(*
** recursive definition of the approximation
*)
fun loop
(
n: int, r: double
) : double =
(
if n = 0
then f.a(0) + r
else loop (n - 1, f.b(n) / (f.a(n) + r))
// end of [if]
)
//
in
loop (n, 0.0)
end // end of [calc]
(* ****** ****** *)
val sqrt2 = @{
a= lam (n: int): double => if n = 0 then 1.0 else 2.0
,
b= lam (n: int): double => 1.0
} (* end of [val] *)
val napier = @{
a= lam (n: int): double => if n = 0 then 2.0 else 1.0 * n
,
b= lam (n: int): double => if n = 1 then 1.0 else n - 1.0
} (* end of [val] *)
val pi = @{
a= lam (n: int): double => if n = 0 then 3.0 else 6.0
,
b= lam (n: int): double => let val x = 2.0 * n - 1 in x * x end
}
(* ****** ****** *)
implement
main0 () =
(
println! ("sqrt2 = ", calc(sqrt2, 100));
println! ("napier = ", calc(napier, 100));
println! (" pi = ", calc( pi , 100));
) (* end of [main0] *)
You may also check:How to resolve the algorithm MD5/Implementation step by step in the Haskell programming language
You may also check:How to resolve the algorithm Archimedean spiral step by step in the Scala programming language
You may also check:How to resolve the algorithm Sum of squares step by step in the ReScript programming language
You may also check:How to resolve the algorithm Rock-paper-scissors step by step in the Rust programming language
You may also check:How to resolve the algorithm Generic swap step by step in the Gri programming language