Skip to content

Commit

Permalink
Add ^ operator support for Rational numbers
Browse files Browse the repository at this point in the history
Since pow() cannot be supported for rationals, we support negative integer exponents instead.
  • Loading branch information
AngelEzquerra committed Jan 16, 2024
1 parent 18b5fb2 commit ac1f0ae
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions lib/pure/rationals.nim
Original file line number Diff line number Diff line change
Expand Up @@ -318,3 +318,23 @@ func hash*[T](x: Rational[T]): Hash =
h = h !& hash(copy.num)
h = h !& hash(copy.den)
result = !$h

func `^`*[T: SomeInteger](x: Rational[T], y: T): Rational[T] =
## Computes `x` to the power of `y`.
##
## The exponent `y` must be an integer. Negative exponents are supported
## but floating point exponents are not.
runnableExamples:
doAssert (-3 // 5) ^ 0 == (1 // 1)
doAssert (-3 // 5) ^ 1 == (-3 // 5)
doAssert (-3 // 5) ^ 2 == (9 // 25)
doAssert (-3 // 5) ^ -2 == (25 // 9)

if y >= 0:
result.num = x.num ^ y
result.den = x.den ^ y
else:
result.num = x.den ^ -y
result.den = x.num ^ -y
# Note that all powers of reduced rationals are already reduced,
# so we don't need to call reduce() here

0 comments on commit ac1f0ae

Please sign in to comment.