-
Notifications
You must be signed in to change notification settings - Fork 0
/
rational.go
144 lines (122 loc) · 2.05 KB
/
rational.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package ops
import (
"math/big"
"github.com/blackchip-org/zc/v5/pkg/zc"
)
/*
oper dec
func DecRational p0:Rational -- Decimal
title Decimal number
desc
Pops *p0* from the stack and formats it as a `Decimal`.
end
example
1/2 dec -- 0.5
end
*/
func DecRational(c zc.Calc) {
a0 := zc.PopRational(c)
r0, exact := a0.Float64()
zc.PushFloat(c, r0)
if !exact {
zc.Annotate(c, "inexact")
}
}
/*
oper denom
func Denom p0:Rational -- BigInt
title Denominator
desc
The denominator of rational number *p0*.
end
example
2/3 denom -- 3
end
*/
func Denom(c zc.Calc) {
a0 := zc.PopRational(c)
r0 := a0.Denom()
zc.PushBigInt(c, r0)
}
/*
oper inv
func Inv p0:Rational -- Rational
title Inverse
desc
Returns the inverse which is 1/*p0*.
end
example
1/2 inv -- 2
end
*/
func Inv(c zc.Calc) {
var r0 big.Rat
a0 := zc.PopRational(c)
r0.Inv(a0)
zc.PushRational(c, &r0)
}
/*
oper is-rational
func IsRational p0:Str -- Bool
title Checks value can be parsed as a rational
desc
Returns `true` if the value *p0* can be parsed as a Rational.
end
example
c 1/2 is-rational -- true
c 1+2i is-rational -- false
end
*/
func IsRational(c zc.Calc) {
a0 := zc.PopString(c)
r0 := zc.Rational.Is(a0)
zc.PushBool(c, r0)
}
/*
oper num
func Num p0:Rational -- BigInt
title Numerator
desc
The numerator of rational number *p0*.
end
example
2/3 num -- 2
end
*/
func Num(c zc.Calc) {
a0 := zc.PopRational(c)
r0 := a0.Num()
zc.PushBigInt(c, r0)
}
/*
oper rational
func RationalBigInt n:BigInt d:BigInt -- Rational
func RationalFloat p0:Float -- Rational
alias rat
title Convert to a Rational
desc
A rational number using an integer numerator *n* and denominator *d*,
or using a floating point value *p0*.
end
example
c 1 2 rat -- 1/2
c 0.5 rat -- 1/2
end
*/
func RationalBigInt(c zc.Calc) {
var r0 big.Rat
d := zc.PopBigInt(c)
n := zc.PopBigInt(c)
r0.SetFrac(n, d)
zc.PushRational(c, &r0)
}
func RationalFloat(c zc.Calc) {
var r0 big.Rat
a0 := zc.PopFloat(c)
res := r0.SetFloat64(a0)
if res == nil {
zc.ErrInvalidArgs(c, "not finite")
return
}
zc.PushRational(c, &r0)
}