I am currently trying to make a function that can tell if number a
is closer to c
than the number b
is to c
.
I have tried to do comparisons like so: (taking a
and b
from c
and comparing those)
$c = 10;
$b = 2;
$a = 3;
$b_check = $c - $b; // = 8.
$a_check = $c - $a; // = 7.
In my head, I thought that whatever number (a
or b
) is smaller means that it's gonna be the closer number to c
, though that worked using positive integers, but when it came to negative integers it gave the complete wrong outcome.
I was wondering if maybe there was an in-built function
in PHP
for this or if there's a better mathematical method for achieving this?
If (a - c) * (a - c) < (b - c) * (b - c)
would do it. This gets round the negative number issue and is the way us old cats do it in C.
Else you could use Math.abs(a - c) < Math.abs(b - c)
but the other way can be quicker for some types, but you need to take care not to overflow your type and there's a potential for a ruinous wraparound effect for some types too.
Profile it.
The one with the smallest absolute value is always the closest. You're thinking in terms of a number line, but it's easier to imagine if you know vectors in 2D or 3D space. Then the distance between two points is the square root of the sum of squares of the difference between their components. The 1D case falls out as a special case where two components are zero.
double distance = Math.sqrt((x2-x1)*(x2-x1)) = Math.abs(x2-x1)