Skip to content

Commit

Permalink
Merge pull request #1212 from arturo-lang/add-neg-overload-for-VRat…
Browse files Browse the repository at this point in the history
…ional-values

Add `neg` overload for VRational values
  • Loading branch information
drkameleon authored Jun 13, 2023
2 parents 17dbd13 + 4507eef commit 784a3cc
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 8 deletions.
10 changes: 7 additions & 3 deletions src/helpers/bignums.nim
Original file line number Diff line number Diff line change
Expand Up @@ -630,9 +630,6 @@ func `*=`*(z: Int, x: int | culong | Int) =
func `*=`*(x, y: Rat) =
discard x.mul(x, y)

func neg*(x: Rat): Rat =
mpq_neg(result[], x[])

func inv*(x: Rat): Rat =
mpq_inv(result[], x[])

Expand Down Expand Up @@ -1080,6 +1077,13 @@ func neg*(x: Int): Int =
func negI*(x: Int) =
mpz_neg(x[], x[])

func neg*(z, x: Rat): Rat =
result = z
mpq_neg(result[], x[])

func neg*(x: Rat): Rat =
newRat().neg(x)

func gcd*(z, x, y: Int): Int =
result = z
mpz_gcd(z[], x[], y[])
Expand Down
15 changes: 15 additions & 0 deletions src/vm/values/custom/vrational.nim
Original file line number Diff line number Diff line change
Expand Up @@ -999,6 +999,21 @@ func abs*(x: VRational): VRational =
br: abs(x.br)
)

func neg*(x: VRational): VRational =
# negation of VRational
if x.rKind == NormalRational:
result = VRational(
rKind: NormalRational,
num: -x.num,
den: x.den
)
else:
when not defined(NOGMP):
result = VRational(
rKind: BigRational,
br: neg(x.br)
)

func floorDiv*(x, y: VRational): int =
# floor division between given VRationals
if x.rKind == NormalRational:
Expand Down
5 changes: 1 addition & 4 deletions src/vm/values/operators.nim
Original file line number Diff line number Diff line change
Expand Up @@ -830,10 +830,7 @@ proc neg*(x: Value): Value =
if x.iKind==NormalInteger: return normalIntegerNeg(x.i)
else: (when GMP: return newInteger(neg(x.bi)))
of Floating: return newFloating(x.f*(-1.0))
# TODO(VRational) add `neg` overload
# it can be faster for BigRational values
# labels: 3rd-party, enhancement, values
of Rational: return newRational(x.rat*(-1))
of Rational: return newRational(neg(x.rat))
of Complex: return newComplex(x.z*(-1.0))
of Quantity: return newQuantity(x.q*(-1))
else:
Expand Down
2 changes: 1 addition & 1 deletion version/build
Original file line number Diff line number Diff line change
@@ -1 +1 @@
856
858

0 comments on commit 784a3cc

Please sign in to comment.