/
ex_rational.go
97 lines (84 loc) · 2.07 KB
/
ex_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
package expreduce
import "fmt"
import "math/big"
import "hash"
type Rational struct {
Num *big.Int
Den *big.Int
}
func (this *Rational) Eval(es *EvalState) Ex {
if this.Num.Cmp(big.NewInt(0)) == 0 && this.Den.Cmp(big.NewInt(0)) == 0 {
return &Symbol{"Indeterminate"}
}
if this.Den.Cmp(big.NewInt(0)) == 0 {
return &Symbol{"ComplexInfinity"}
}
if this.Num.Cmp(big.NewInt(0)) == 0 {
return &Integer{big.NewInt(0)}
}
negNum := this.Num.Cmp(big.NewInt(0)) == -1
negDen := this.Den.Cmp(big.NewInt(0)) == -1
negateRes := negNum != negDen
absNum := big.NewInt(0)
absNum.Abs(this.Num)
absDen := big.NewInt(0)
absDen.Abs(this.Den)
gcd := big.NewInt(0)
gcd.GCD(nil, nil, absNum, absDen)
absNum.Div(absNum, gcd)
absDen.Div(absDen, gcd)
if absDen.Cmp(big.NewInt(1)) == 0 {
if !negateRes {
return &Integer{absNum}
} else {
return &Integer{absNum.Neg(absNum)}
}
}
if !negateRes {
this.Num.Set(absNum)
this.Den.Set(absDen)
return this
} else {
this.Num.Set(absNum.Neg(absNum))
this.Den.Set(absDen)
return this
}
return this
}
func (this *Rational) StringForm(form string) string {
return fmt.Sprintf("%d/%d", this.Num, this.Den)
}
func (this *Rational) String() string {
return this.StringForm("InputForm")
}
func (this *Rational) IsEqual(other Ex, cl *CASLogger) string {
otherConv, otherIsRational := other.(*Rational)
if !otherIsRational {
return "EQUAL_FALSE"
}
// Assume rational already simplified
if (this.Num.Cmp(otherConv.Num) != 0) || (this.Den.Cmp(otherConv.Den) != 0) {
return "EQUAL_FALSE"
}
return "EQUAL_TRUE"
}
func (this *Rational) DeepCopy() Ex {
tmpn := big.NewInt(0)
tmpn.Set(this.Num)
tmpd := big.NewInt(0)
tmpd.Set(this.Den)
return &Rational{tmpn, tmpd}
}
func (this *Rational) AsBigRat() *big.Rat {
return big.NewRat(this.Num.Int64(), this.Den.Int64())
}
func (this *Rational) NeedsEval() bool {
return false
}
func (this *Rational) Hash(h *hash.Hash64) {
(*h).Write([]byte{90, 82, 214, 51, 52, 7, 7, 33})
nBytes, _ := this.Num.MarshalText()
(*h).Write(nBytes)
dBytes, _ := this.Den.MarshalText()
(*h).Write(dBytes)
}