summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authorAngel Ezquerra <AngelEzquerra@users.noreply.github.com>2024-01-18 14:32:22 +0100
committerGitHub <noreply@github.com>2024-01-18 14:32:22 +0100
commit2425f4559cc5e8a96cf0dccea72817a782918de0 (patch)
tree603080af5e4ee0a28910cbf1c27e67ec571eddfd /lib
parent3379d26629f30e6be8d303a36e220d1039eb4551 (diff)
downloadNim-2425f4559cc5e8a96cf0dccea72817a782918de0.tar.gz
Add `^` operator support for Rational numbers (#23219)
Since pow() cannot be supported for rationals, we support negative
integer exponents instead.
Diffstat (limited to 'lib')
-rw-r--r--lib/pure/rationals.nim20
1 files changed, 20 insertions, 0 deletions
diff --git a/lib/pure/rationals.nim b/lib/pure/rationals.nim
index 45902b7cd..5f806bd70 100644
--- a/lib/pure/rationals.nim
+++ b/lib/pure/rationals.nim
@@ -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