-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconsumers.go
92 lines (79 loc) · 1.93 KB
/
consumers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Copyright 2017 Andreas Pannewitz. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ps
import (
"fmt"
)
// ===========================================================================
// Consumers: Eval & Print
// Conventions
// Upper-case for power series.
// Lower-case for coefficients.
// Input variables: U,V,...
// Output variables: ...,Y,Z
// EvalAt evaluates a power series at `x=c`
// for up to `n` terms,
// where `n=1` denotes the first, the constant term.
func (U PS) EvalAt(c Coefficient, n int) Coefficient {
u, ok := U.Receive()
switch {
case ok && n == 1:
return u
case ok && n > 1:
return cAdd(u)(cMul(c)(U.EvalAt(c, n-1))) // `u + c*U`
default:
U.Drop()
return aZero()
}
}
// EvalN evaluates a power series at `x=c`
// for up to `n` terms in floating point,
// where `n=1` denotes the first, the constant term.
func (U PS) EvalN(c Coefficient, n int) float64 {
ci := float64(1)
fc, _ := c.Float64()
val := float64(0)
var u Coefficient
var fu float64
var ok bool
for i := 0; i < n; i++ {
if u, ok = U.Receive(); !ok {
break
}
fu, _ = u.Float64()
val += fu * ci // val += `u(i) * c^i`
ci = fc * ci // `c^(i+1) = c * c^i`
}
U.Drop()
return val
}
// Printn prints up to n terms of a power series.
func (U PS) Printn(n int) {
defer fmt.Print("\n")
var u Coefficient
var ok bool
for ; n > 0; n-- {
if u, ok = U.Receive(); !ok {
break
}
fmt.Print(u.String())
fmt.Print(" ")
}
U.Drop()
}
// Printer returns a copy of `U`,
// and concurrently prints up to n terms of it.
// Useful to inspect formulas as it can be chained.
func (U PS) Printer(n int) PS {
UC, UP := U.Split()
go func(U PS, n int) {
U.Printn(n)
}(UP, n)
return UC
}
// Print one billion terms. Use at Your own risk ;-)
func (U PS) Print() {
U.Printn(1000000000)
}
// ===========================================================================