psalaets/line-intersect

Floating point rounding errors on horizontal/vertical intersection

david-abell opened this issue · 2 comments

I'm getting some float rounding errors when using this module to calculate intersections of vertical and horizontal lines of unsorted data.

Expected result:

{ type: 'intersecting', point: { x: 453, y: 242 } }

When calling:

console.log(checkIntersection(952, 242, 178, 242, 453, 860, 453, 196));

The resulting log to console is:

{ type: 'intersecting', point: { x: 453.00000000000006, y: 242 } }

Reversing the line order like below:

console.log(checkIntersection(453, 860, 453, 196, 952, 242, 178, 242)

results in the expected output:

{ type: 'intersecting', point: { x: 453, y: 242 } }

When comparing the below lines:
line1: 952,242 -> 178,242
line2: 453,860 -> 453,196
line3: 75,380 -> 956,380
line4: 696,821 -> 696,198

I get the below output:

line1: 952,242,178,242, line2 453,860,453,196, point x,453.00000000000006,y,242
line2: 453,860,453,196, line1 952,242,178,242, point x,453,y,242
line1: 952,242,178,242, line4 696,821,696,198, point x,696,y,242
line1: 453,860,453,196, line3 75,380,956,380, point x,453,y,380
line3: 75,380,956,380, line4 696,821,696,198, point x,696,y,380
line4: 696,821,696,198, line3 75,380,956,380, point x,696,y,380.00000000000006

This looks like a side effect of how numbers are represented in JavaScript.

Here are some posts about what you're seeing and how to work around it:

It's definitely the Javascript numbers problem. I fixed it in my end with Math.round.

Figured I'd check whether it was a known side effect as I didn't see anything in the readme on whether it was handled by your package or not.