Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions pico8lib/math.lua
Original file line number Diff line number Diff line change
Expand Up @@ -85,17 +85,6 @@ end

-- partially thanks to https://www.lexaloffle.com/bbs/?pid=119363

--- Distance to a point
-- Uses `dist_naive` for small values, `dist_trig` for large
-- tokens: 46
-- @tparam number x X coordinate of the point
-- @tparam number y Y coordinate of the point
-- @treturn number Distance from 0,0 to x,y
local function dist(x,y)
if (abs(x) < 128 and abs(y) < 128) return dist_naive(x,y)
return dist_trig(x,y)
end

--- Distance to a point
-- Naive distance calculation
-- Overflows for dist^2>=32768
Expand All @@ -121,6 +110,17 @@ local function dist_trig(x,y)
return x*cos(a)+y*sin(a)
end

--- Distance to a point
-- Uses `dist_naive` for small values, `dist_trig` for large
-- tokens: 46
-- @tparam number x X coordinate of the point
-- @tparam number y Y coordinate of the point
-- @treturn number Distance from 0,0 to x,y
local function dist(x,y)
if (abs(x) < 128 and abs(y) < 128) return dist_naive(x,y)
return dist_trig(x,y)
end

--- Distance squared to a point
-- @tparam number x X coordinate of the point
-- @tparam number y Y coordinate of the point
Expand Down
13 changes: 13 additions & 0 deletions tests/test_math.p8
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,19 @@ suite:add_test_case(Nthroot)
-- Distancefunctions
local Distance = TestCase("distance")

function Distance:test_dist_exact ()
for _,v in ipairs({
{0,0,0},
{1,1,sqrt(2)},
{3,4,5},
{44,117,125},
})
do
self:assert_equal(dist(v[1],v[2]), v[3])
self:assert_equal(dist(v[2],v[1]), v[3])
end
end

function Distance:test_dist_naive_exact ()
for _,v in ipairs({
{0,0,0},
Expand Down