So my case goes like this, my software that is being develop on JavaScript needs to manipulate exact numeric values but sometimes it can happen that the values are way too near and I need to discriminate.
This is a case example:
0:(2) [112.02598008561951, 9.12963236661007]
1:(2) [112.02598008561952, 9.129632366610064]
2:(2) [9.751846481442218, 3.5376744911193576]
In this array position 0 and 1 has similar values but with an slight difference at the end of the decimals, but the one that counts is the position 0, because the two numbers are way near it messes with the process that follows next.
So, how do I do to discriminate near numbers and just use the first of the similar numbers given?
In the end the end result would be an array like this:
0:(2) [112.02598008561951, 9.12963236661007]
1:(2) [9.751846481442218, 3.5376744911193576]
I tried doing a truncation but I need the whole number to work with.
Edit: as one of the comments asked about if the points can vary or not, in my real problem I get a series of numbers that I sort normally I get like 3 points or best case scenario I get 2 points.
Sometimes this problem happens when I get near numbers and the first layer of sorting doesn’t work as intended and the next part doesn’t work well.
In short, you need to consider that it is always like 3 positions of coordinates.
>Solution :
Let’s see if I understood correctly, you have this array with vertex points, usually it’s just a 2 elements bidimensional array, but sometimes it might receive an extra vertex points array, with a slight different value (differ of 1*10^-14) and you want to discard the higher extra values.
I came up with something like this:
const arr = [
[112.02598008561951, 9.12963236661007],
[112.02598008561952, 9.129632366610064],
[9.751846481442218, 3.5376744911193576],
];
for (let i = 0; i < arr.length-1; i++) {
const diff = Math.abs(arr[i][0] - arr[i + 1][0])
if (diff <= 0.00000000000002) arr.splice(i + 1, 1);
}
console.log("NEW ARR", arr)
This just checks the first element of the array, since if I understood correctly it automatically means even the second element differs of a similar amount.
I’m using a (2*10-14) threshold since 1 is not enough, not sure if it’s due to JS issues with float precision.