Implement numeric operations in-place

This commit is contained in:
Jan Bader 2022-03-04 20:54:23 +00:00
parent 67c013799d
commit 3795150508

View File

@ -53,6 +53,13 @@ func (n Numeric) IsZero() bool {
return float == 0 return float == 0
} }
func (n *Numeric) MatchExpI(exp int32) {
diffExp := n.Exp - exp
factor := big.NewInt(0).Exp(big.NewInt(10), big.NewInt(int64(diffExp)), nil) //nolint:gomnd
n.Exp = exp
n.Int = big.NewInt(0).Mul(n.Int, factor)
}
func (n Numeric) MatchExp(exp int32) Numeric { func (n Numeric) MatchExp(exp int32) Numeric {
diffExp := n.Exp - exp diffExp := n.Exp - exp
factor := big.NewInt(0).Exp(big.NewInt(10), big.NewInt(int64(diffExp)), nil) //nolint:gomnd factor := big.NewInt(0).Exp(big.NewInt(10), big.NewInt(int64(diffExp)), nil) //nolint:gomnd
@ -64,6 +71,22 @@ func (n Numeric) MatchExp(exp int32) Numeric {
}} }}
} }
func (n *Numeric) SubI(other Numeric) *Numeric {
right := other
if n.Exp < other.Exp {
right = other.MatchExp(n.Exp)
} else if n.Exp > other.Exp {
n.MatchExpI(other.Exp)
}
if n.Exp == right.Exp {
n.Int = big.NewInt(0).Sub(n.Int, right.Int)
return n
}
panic("Cannot subtract with different exponents")
}
func (n Numeric) Sub(other Numeric) Numeric { func (n Numeric) Sub(other Numeric) Numeric {
left := n left := n
right := other right := other
@ -106,6 +129,22 @@ func (n Numeric) Add(other Numeric) Numeric {
panic("Cannot add with different exponents") panic("Cannot add with different exponents")
} }
func (n *Numeric) AddI(other Numeric) *Numeric {
right := other
if n.Exp < other.Exp {
right = other.MatchExp(n.Exp)
} else if n.Exp > other.Exp {
n.MatchExpI(other.Exp)
}
if n.Exp == right.Exp {
n.Int = big.NewInt(0).Add(n.Int, right.Int)
return n
}
panic("Cannot add with different exponents")
}
func (n Numeric) String() string { func (n Numeric) String() string {
if n.Int == nil || n.Int.Int64() == 0 { if n.Int == nil || n.Int.Int64() == 0 {
return "0" return "0"