Merge pull request #3406 from jlp765/rationals1
Rationals - add checks and tests
This commit is contained in:
commit
f8b7a16ad0
3 changed files with 23 additions and 3 deletions
|
|
@ -18,8 +18,9 @@ type Rational*[T] = object
|
||||||
## a rational number, consisting of a numerator and denominator
|
## a rational number, consisting of a numerator and denominator
|
||||||
num*, den*: T
|
num*, den*: T
|
||||||
|
|
||||||
proc initRational*[T](num, den: T): Rational[T] =
|
proc initRational*[T:SomeInteger](num, den: T): Rational[T] =
|
||||||
## Create a new rational number.
|
## Create a new rational number.
|
||||||
|
assert(den != 0, "a denominator of zero value is invalid")
|
||||||
result.num = num
|
result.num = num
|
||||||
result.den = den
|
result.den = den
|
||||||
|
|
||||||
|
|
@ -33,7 +34,7 @@ proc `$`*[T](x: Rational[T]): string =
|
||||||
## Turn a rational number into a string.
|
## Turn a rational number into a string.
|
||||||
result = $x.num & "/" & $x.den
|
result = $x.num & "/" & $x.den
|
||||||
|
|
||||||
proc toRational*[T](x: T): Rational[T] =
|
proc toRational*[T:SomeInteger](x: T): Rational[T] =
|
||||||
## Convert some integer `x` to a rational number.
|
## Convert some integer `x` to a rational number.
|
||||||
result.num = x
|
result.num = x
|
||||||
result.den = 1
|
result.den = 1
|
||||||
|
|
@ -47,7 +48,7 @@ proc toInt*[T](x: Rational[T]): int =
|
||||||
## `x` does not contain an integer value.
|
## `x` does not contain an integer value.
|
||||||
x.num div x.den
|
x.num div x.den
|
||||||
|
|
||||||
proc reduce*[T](x: var Rational[T]) =
|
proc reduce*[T:SomeInteger](x: var Rational[T]) =
|
||||||
## Reduce rational `x`.
|
## Reduce rational `x`.
|
||||||
let common = gcd(x.num, x.den)
|
let common = gcd(x.num, x.den)
|
||||||
if x.den > 0:
|
if x.den > 0:
|
||||||
|
|
|
||||||
9
tests/rational/trat_float.nim
Normal file
9
tests/rational/trat_float.nim
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
discard """
|
||||||
|
file: "trat_float.nim"
|
||||||
|
line: "9,19"
|
||||||
|
errormsg: '''type mismatch: got'''
|
||||||
|
"""
|
||||||
|
import rationals
|
||||||
|
var
|
||||||
|
# this fails - no floats as num or den
|
||||||
|
r = initRational(1.0'f, 1.0'f)
|
||||||
10
tests/rational/trat_init.nim
Normal file
10
tests/rational/trat_init.nim
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
discard """
|
||||||
|
file: "trat_init.nim"
|
||||||
|
exitcode: "1"
|
||||||
|
"""
|
||||||
|
import rationals
|
||||||
|
var
|
||||||
|
z = Rational[int](num: 0, den: 1)
|
||||||
|
o = initRational(num=1, den=1)
|
||||||
|
a = initRational(1, 2)
|
||||||
|
r = initRational(1, 0) # this fails - no zero denominator
|
||||||
Loading…
Add table
Add a link
Reference in a new issue