From a26131ab6e12da171829e360867bdf9de280fbea Mon Sep 17 00:00:00 2001 From: neviyn Date: Tue, 21 Jul 2020 14:32:09 +0100 Subject: [PATCH] Better float comparisons --- src/tuple.nim | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/tuple.nim b/src/tuple.nim index f5ff582..edeac61 100644 --- a/src/tuple.nim +++ b/src/tuple.nim @@ -1,9 +1,17 @@ from math import sqrt +const + eps = 1.0e-7 ## Epsilon used for float comparisons. + +proc `=~` *(x, y: float): bool = + result = abs(x - y) < eps + type Tuple4* = object x*, y*, z*, w*: float +proc `==`*(lhs, rhs: Tuple4): bool = lhs.x =~ rhs.x and lhs.y =~ rhs.y and lhs.z =~ rhs.z and lhs.w =~ rhs.w + proc point*(x: float, y: float, z: float): Tuple4 = Tuple4(x: x, y: y, z: z, w: 1) proc vector*(x: float, y: float, z: float): Tuple4 = Tuple4(x: x, y: y, z: z, w: 0) @@ -11,8 +19,8 @@ proc vector*(x: float, y: float, z: float): Tuple4 = Tuple4(x: x, y: y, z: z, w: proc isPoint*(target: Tuple4): bool = target.w == 1 proc isVector*(target: Tuple4): bool = target.w == 0 -proc `+`*(lhs: Tuple4, rhs: Tuple4): Tuple4 = Tuple4(x: lhs.x + rhs.x, y: lhs.y + rhs.y, z: lhs.z + rhs.z, w: lhs.w + rhs.w) -proc `-`*(lhs: Tuple4, rhs: Tuple4): Tuple4 = Tuple4(x: lhs.x - rhs.x, y: lhs.y - rhs.y, z: lhs.z - rhs.z, w: lhs.w - rhs.w) +proc `+`*(lhs, rhs: Tuple4): Tuple4 = Tuple4(x: lhs.x + rhs.x, y: lhs.y + rhs.y, z: lhs.z + rhs.z, w: lhs.w + rhs.w) +proc `-`*(lhs, rhs: Tuple4): Tuple4 = Tuple4(x: lhs.x - rhs.x, y: lhs.y - rhs.y, z: lhs.z - rhs.z, w: lhs.w - rhs.w) proc `-`*(tup: Tuple4): Tuple4 = Tuple4(x: -tup.x, y: -tup.y, z: -tup.z, w: -tup.w) proc `*`*(tup: Tuple4, mag: float): Tuple4 = Tuple4(x: tup.x * mag, y: tup.y * mag, z: tup.z * mag, w: tup.w * mag) proc `/`*(tup: Tuple4, mag: float): Tuple4 = Tuple4(x: tup.x / mag, y: tup.y / mag, z: tup.z / mag, w: tup.w / mag) @@ -21,8 +29,8 @@ proc magnitude*(tup: Tuple4): float = sqrt(tup.x * tup.x + tup.y * tup.y + tup.z proc normalize*(tup: Tuple4): Tuple4 = let mag = tup.magnitude() Tuple4(x: tup.x / mag, y: tup.y / mag, z: tup.z / mag, w: tup.w / mag) -proc dot*(lhs: Tuple4, rhs: Tuple4): float = lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z + lhs.w * rhs.w -proc cross*(lhs: Tuple4, rhs: Tuple4): Tuple4 = vector(lhs.y * rhs.z - lhs.z * rhs.y, lhs.z * rhs.x - lhs.x * rhs.z, lhs.x * rhs.y - lhs.y * rhs.x) +proc dot*(lhs, rhs: Tuple4): float = lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z + lhs.w * rhs.w +proc cross*(lhs, rhs: Tuple4): Tuple4 = vector(lhs.y * rhs.z - lhs.z * rhs.y, lhs.z * rhs.x - lhs.x * rhs.z, lhs.x * rhs.y - lhs.y * rhs.x) when isMainModule: import unittest