Python Forum

Full Version: Problem with simple 3D Vektor calculation
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello!

I am trying to do a simple vector calculation. But somehow it is not correct an I can not find the error.
Basically I have a vector with a start and endpoint, both somewhere in the 3D space.
Then I give a point p. I then try to calculate the minimum distance between point and vector and the point f where the minimum distance is. The result of the whole thing is a percentage, where the f point is according to the given vector. If the point is below the startpoint the percentage is simply minus, if it exceeds the end point the percentage is above 100.
All works as long as I put the vector on one of the origin surfaces (like 2D). But as soon as I try it in 3D the result is incorrect. I can not find an error in my calculation yet the result is wrong. The vector is chorter then the two vectors from start to f and end to f combined.

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import math, sys

def vec_len(lx1, ly1, lz1, lx2, ly2, lz2):
	return math.sqrt(((lx1-lx2)**2)+((ly1-ly2)**2)+((lz1+lz2)**2))

def vector(lx1, ly1, lz1, lx2, ly2, lz2):
	ax.plot([lx1,lx2], [ly1,ly2],zs=[lz1,lz2])

def point(x, y, z):
	ax.scatter(x, y, z, c='r', marker='o')

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x1 = 10
y1 = 50
z1 = 40
x2 = 50
y2 = 10
z2 = 0
px = 70
py = 70
pz = 70

vector(x1, y1, z1, x2, y2, z2)
point(px, py, pz)

xn = x2 - x1
yn = y2 - y1
zn = z2 - z1

d = (xn * px) + (yn * py) + (zn * pz)

s = (d - (xn*x1) - (yn*y1) - (zn*z1)) / ((xn**2) + (yn**2) + (zn**2))

fx = x1 + s * xn
fy = y1 + s * yn
fz = z1 + s * zn

point(fx, fy,fz)

#vector(fx, fy, fz, px, py, pz)

la = vec_len(x1, y1, z1, fx, fy, fz)
lb = vec_len(x2, y2, z2, fx, fy, fz)
lg = vec_len(x1, y1, z1, x2, y2, z2)

#vector(x1, y1, z1, fx, fy, fz)
#vector(x2, y2, z2, fx, fy, fz)
#vector(x1, y1, z1, x2, y2, z2)

print(la)
print(lb)
print(lg)

if(((la + lb) > lg) and (la < lb)):
	percentage = (100.0 / lg) * -la
else:
	percentage = (100.0 / lg) * la

distance = vec_len(fx, fy, fz, px, py, pz)

print(percentage)
print(distance)

sys.stdout.flush()

ax.set_xlim([0,100])
ax.set_ylim([100,0])
ax.set_zlim([0,100])
plt.show()


Does anyone see an error?

Thanks!

Seems there was a problem using x**2 with brackets...