1
0

Better float comparisons

This commit is contained in:
neviyn 2020-07-21 14:32:09 +01:00
parent 464401781e
commit a26131ab6e

View File

@ -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