I am making this very simple program which calculates the distance between the coordinates of a player and the coordinates of another place (for Minecraft).
import math
px = int(input("Your x-coordinate: "))
pz = int(input("Your z-coordinate: "))
x = int(input("X-coordinate of destination: "))
z = int(input("z-coordinate of destination: "))
dist = math.sqrt((px-x)^2+(pz-z)^2)
print("Distance is %d meters." % dist)
When I enter (0, 0) as my coordinates and (1, 1) as the other place's coordinates, Python returns "ValueError: math domain error" instead of the expected value of root 2. Though when I enter (0, 0) as both my coordinates AND the other place's coordinates, Python returns "0". Can someone please identify the issue for me and a possible solution?
In
dist = math.sqrt((px-x)^2+(pz-z)^2)
The ^
symbol is used for the bitwise XOR operation. For taking power, you should use either math.pow()
or **
, i.e.,
dist = math.sqrt((px-x)**2+(pz-z)**2)
Alternatively, you can also use math.hypot()
:
dist = math.hypot(px-x, pz-z)