'Finding distance between 2 coordinates in solidity
It is said that distance is equal to the following formula:
distance = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
I do this exact formula in the function below. However, the problem I run into is when x2 is less than x1, for example, I get an error because uint256 can't be negative.
Does anyone know how I can account for this in solidity when calculating distance?
function getDistance(uint256 x1, uint256 x2, uint256 y1, uint256 y1, ) private view returns(uint256) {
return sqrt(((x2 - x1)**2) + ((y2 - y1)**2));
}
function sqrt(uint x) private pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
Solution 1:[1]
Instead of using uint256 use int256 so you can accept negative number
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohamad Al Zohbie |
