Anonymous user
Continued fraction/Arithmetic/G(matrix ng, continued fraction n): Difference between revisions
Continued fraction/Arithmetic/G(matrix ng, continued fraction n) (view source)
Revision as of 14:55, 27 June 2018
, 5 years ago→{{header|Go}}: Update Go to match other Continued_fraction/* tasks.
(→{{header|Go}}: Add Go solution) |
(→{{header|Go}}: Update Go to match other Continued_fraction/* tasks.) |
||
Line 176:
=={{header|Go}}==
[[Continued_fraction/Arithmetic/Construct_from_rational_number#Go]]
task, re-uses <code>cf.go</code> and <code>rat.go</code> as given in that task.
File <code>ng8.go</code>:
<lang Go>package cf
// A 2×2 matix:
// [ a₁ a ]
// [ b₁ b ]
//
// which when "applied" to a continued fraction representing x
// gives a new continued fraction z such that:
//
// a₁ * x + a
// z = ----------
// b₁ * x + b
//
// Examples:
// NG4{0, 1, 0, 4}.ApplyTo(x) gives 0*x + 1/4 -> 1/4 = [0; 4]
// NG4{0, 1, 1, 0}.ApplyTo(x) gives 1/x
// NG4{1, 1, 0, 2}.ApplyTo(x) gives (x+1)/2
//
// Note that several operations (e.g. addition and division)
// can be efficiently done with a single matrix application.
// However, each matrix application may require
// several calculations for each outputed term.
type NG4 struct {
A1, A int64
B1, B int64
}
func (
if ng.isDone() {
panic("b₁==b==0")
}
return ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B
}
func (ng NG4) isDone() bool {
return ng.B1 == 0 && ng.B == 0
}
Line 218 ⟶ 222:
// [ a₁ a ] becomes [ a + a₁×t a₁ ]
// [ b₁ b ] [ b + b₁×t b₁ ]
ng
ng
ng
}
func (ng *NG4) ingestInfinite() {
// [ a₁ a ] becomes [ a₁ a₁ ]
// [ b₁ b ] [ b₁ b₁ ]
ng.A, ng.B = ng.A1, ng.B1
}
Line 226 ⟶ 236:
// [ a₁ a ] becomes [ b₁ b ]
// [ b₁ b ] [ a₁ - b₁×t a - b×t ]
ng
ng
ng
}
// ApplyTo "applies" the matrix `ng` to the continued fraction `cf`,
// returning the resulting continued fraction.
func (ng NG4) ApplyTo(cf ContinuedFraction) ContinuedFraction {
return
next := cf()
done := false
return func() (int64, bool) {
if done {
return 0, false
}
if t,
} else {
}
}
t := ng.A1 / ng.B1
ng.egest(t)
done = ng.isDone()
return t, true
}
}
}</lang>
File <code>ng4_test.go</code>:
<lang Go>package cf
import (
"fmt"
"reflect"
"testing"
)
func Example_NG4(
cases := [...]struct {
r Rat
Line 307 ⟶ 285:
for _, tc := range cases {
cf := tc.r.AsContinuedFraction()
fmt.Printf("%5s = %-9s with %v gives %
tc.ng.ApplyTo(cf),
)
Line 316 ⟶ 294:
result := NG4{1, 1, 0, 2}.ApplyTo(Sqrt2)
fmt.Println("(1+√2)/2 =", result)
// Output:
// 13/11 = [1; 5, 2] with {2 1 0 2} gives [1; 1, 2, 7]
// 22/7 = [3; 7] with {2 1 0 2} gives [3; 1, 1, 1, 4]
// 22/7 = [3; 7] with {1 0 0 4} gives [0; 1, 3, 1, 2]
// 1/√2 = [0; 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, ...]
// (1+√2)/2 = [1; 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, ...]
}</lang>
{{out}}
<pre>
13/11 = [1; 5, 2] with
22/7 = [3; 7] with
22/7 = [3; 7] with
1/√2 = [0; 1
(1+√2)/2 = [1;
</pre>
|