How to resolve the algorithm Continued fraction/Arithmetic/Construct from rational number step by step in the Go programming language
How to resolve the algorithm Continued fraction/Arithmetic/Construct from rational number step by step in the Go programming language
Table of Contents
Problem Statement
The purpose of this task is to write a function
r 2 c f
(
i n t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i n t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r 2 c f
(
F r a c t i o n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N )
{\displaystyle N)}
, which will output a continued fraction assuming: The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a b s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero. Demonstrate the function by outputing the continued fraction for:
2
{\displaystyle {\sqrt {2}}}
should approach
[ 1 ; 2 , 2 , 2 , 2 , … ]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you: Try : Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[ 3 ; 7 ]
{\displaystyle [3;7]}
may be represented as
[ 3 ; 7 , ∞ ]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Continued fraction/Arithmetic/Construct from rational number step by step in the Go programming language
The provided Go code defines data types and functions to represent and manipulate continued fractions. Here's a detailed explanation of each part of the code:
Package Definition:
package cf
This line defines a Go package named cf
, which will contain the code for continued fractions.
Continued Fraction Representation:
type ContinuedFraction func() NextFn
ContinuedFraction
is a type alias for a function that returns a NextFn
. A ContinuedFraction
represents an infinite sequence of numbers that can be generated using the NextFn
function.
type NextFn func() (term int64, ok bool)
NextFn
is a type alias for a function that returns two values: term
, which is the next number in the continued fraction, and ok
, which indicates whether there are more terms in the sequence.
Stringer Implementation for ContinuedFraction:
func (cf ContinuedFraction) String() string {
// ...
}
This function implements the fmt.Stringer
interface for ContinuedFraction
. It converts a continued fraction into a human-readable string representation and displays a maximum of 20 terms. If the sequence is longer, it ends with ", ...".
Predefined Continued Fraction Formulas:
func Sqrt2() NextFn
func Phi() NextFn
func E() NextFn
These functions define predefined continued fractions for √2, the golden ratio (ϕ), and e. They return NextFn
functions that generate the terms of these continued fractions.
Converting Rational Numbers to Continued Fractions:
type Rat struct {
N, D int64
}
Rat
is a type that represents a rational number as a quotient of two integers, N
and D
.
func (r Rat) String() string
This function implements the fmt.Stringer
interface for Rat
. It returns a string representation of the rational number in the form "N/D".
func (r Rat) AsContinuedFraction() ContinuedFraction
This function returns a continued fraction representation of the Rat
value. It is implemented using the CFTerms
function below.
func (r Rat) CFTerms() NextFn
This function generates the terms of the continued fraction representation of the Rat
value. It uses a simple algorithm to calculate the next term in the fraction.
func r2cf(n1, n2 int64) ContinuedFraction
This function is a convenience function for converting a pair of integers (n1
and n2
) into a continued fraction representation. It is used in the Rosetta Code task.
Example Usage:
func Example_ConstructFromRational() {}
This is an example function that demonstrates how to create and use Rat
and ContinuedFraction
types. It prints the continued fraction representations of various rational numbers.
func Example_Approximating() {}
This example function demonstrates how to approximate irrational numbers (like √2, π, ϕ, and e) using continued fractions. It prints the approximations for different numbers of terms and compares them to the actual values.
Source code in the go programming language
package cf
import (
"fmt"
"strings"
)
// ContinuedFraction is a regular continued fraction.
type ContinuedFraction func() NextFn
// NextFn is a function/closure that can return
// a posibly infinite sequence of values.
type NextFn func() (term int64, ok bool)
// String implements fmt.Stringer.
// It formats a maximum of 20 values, ending the
// sequence with ", ..." if the sequence is longer.
func (cf ContinuedFraction) String() string {
var buf strings.Builder
buf.WriteByte('[')
sep := "; "
const maxTerms = 20
next := cf()
for n := 0; ; n++ {
t, ok := next()
if !ok {
break
}
if n > 0 {
buf.WriteString(sep)
sep = ", "
}
if n >= maxTerms {
buf.WriteString("...")
break
}
fmt.Fprint(&buf, t)
}
buf.WriteByte(']')
return buf.String()
}
// Sqrt2 is the continued fraction for √2, [1; 2, 2, 2, ...].
func Sqrt2() NextFn {
first := true
return func() (int64, bool) {
if first {
first = false
return 1, true
}
return 2, true
}
}
// Phi is the continued fraction for ϕ, [1; 1, 1, 1, ...].
func Phi() NextFn {
return func() (int64, bool) { return 1, true }
}
// E is the continued fraction for e,
// [2; 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10, 1, 1, 12, ...].
func E() NextFn {
var i int
return func() (int64, bool) {
i++
switch {
case i == 1:
return 2, true
case i%3 == 0:
return int64(i/3) * 2, true
default:
return 1, true
}
}
}
package cf
import "fmt"
// A Rat represents a quotient N/D.
type Rat struct {
N, D int64
}
// String implements fmt.Stringer and returns a string
// representation of `r` in the form "N/D" (even if D == 1).
func (r Rat) String() string {
return fmt.Sprintf("%d/%d", r.N, r.D)
}
// As ContinuedFraction returns a contined fraction representation of `r`.
func (r Rat) AsContinuedFraction() ContinuedFraction { return r.CFTerms }
func (r Rat) CFTerms() NextFn {
return func() (int64, bool) {
if r.D == 0 {
return 0, false
}
q := r.N / r.D
r.N, r.D = r.D, r.N-q*r.D
return q, true
}
}
// Rosetta Code task explicitly asked for this function,
// so here it is. We'll just use the types above instead.
func r2cf(n1, n2 int64) ContinuedFraction { return Rat{n1, n2}.CFTerms }
package cf
import (
"fmt"
"math"
)
func Example_ConstructFromRational() {
cases := [...]Rat{
{1, 2},
{3, 1},
{23, 8},
{13, 11},
{22, 7},
{-151, 77},
}
for _, r := range cases {
fmt.Printf("%7s = %s\n", r, r.AsContinuedFraction())
}
for _, tc := range [...]struct {
name string
approx float64
cf ContinuedFraction
d1, d2 int64
}{
{"√2", math.Sqrt2, Sqrt2, 1e4, 1e8},
{"π", math.Pi, nil, 10, 1e10},
{"ϕ", math.Phi, Phi, 10, 1e5},
{"e", math.E, E, 1e5, 1e9},
} {
fmt.Printf("\nApproximating %s ≅ %v:\n", tc.name, tc.approx)
for d := tc.d1; d < tc.d2; d *= 10 {
n := int64(math.Round(tc.approx * float64(d)))
r := Rat{n, d}
fmt.Println(r, "=", r.AsContinuedFraction())
}
if tc.cf != nil {
wid := int(math.Log10(float64(tc.d2)))*2 + 2 // ick
fmt.Printf("%*s: %v\n", wid, "Actual", tc.cf)
}
}
// Output:
// [… commented output used by go test omitted for
// Rosetta Code listing; it is the same as below …]
}
You may also check:How to resolve the algorithm Greatest element of a list step by step in the hexiscript programming language
You may also check:How to resolve the algorithm Interactive programming (repl) step by step in the Picat programming language
You may also check:How to resolve the algorithm Determine if a string is collapsible step by step in the Nim programming language
You may also check:How to resolve the algorithm Ethiopian multiplication step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Averages/Root mean square step by step in the EasyLang programming language