How to resolve the algorithm Continued fraction step by step in the CoffeeScript programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Continued fraction step by step in the CoffeeScript 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 CoffeeScript programming language

Source code in the coffeescript programming language

# Compute a continuous fraction of the form
# a0 + b1 / (a1 + b2 / (a2 + b3 / ...
continuous_fraction = (f) ->
  a = f.a
  b = f.b
  c = 1
  for n in [100000..1]
    c = b(n) / (a(n) + c)
  a(0) + c

# A little helper.
p = (a, b) ->
  console.log a
  console.log b
  console.log "---"

do ->
  fsqrt2 =
    a: (n) -> if n is 0 then 1 else 2
    b: (n) -> 1
  p Math.sqrt(2), continuous_fraction(fsqrt2)

  fnapier =
    a: (n) -> if n is 0 then 2 else n
    b: (n) -> if n is 1 then 1 else n - 1
  p Math.E, continuous_fraction(fnapier)

  fpi =
    a: (n) ->
      return 3 if n is 0
      6
    b: (n) ->
      x = 2*n - 1
      x * x
  p Math.PI, continuous_fraction(fpi)


  

You may also check:How to resolve the algorithm Rosetta Code/Count examples step by step in the R programming language
You may also check:How to resolve the algorithm Array length step by step in the F# programming language
You may also check:How to resolve the algorithm First-class functions step by step in the Ursala programming language
You may also check:How to resolve the algorithm Knapsack problem/0-1 step by step in the VBScript programming language
You may also check:How to resolve the algorithm Loops/Infinite step by step in the Fish programming language