7

I have a plane, plane A, defined by its orthogonal vector, say (a, b, c).

(i.e. the vector (a, b, c) is orthogonal to plane A)

I wish to project a vector (d, e, f) onto plane A.

How can I do it in Python? I think there must be some easy ways.

BuschnicK
  • 5,154
  • 7
  • 36
  • 48
Sibbs Gambling
  • 18,128
  • 38
  • 90
  • 168

1 Answers1

9

Take (d, e, f) and subtract off the projection of it onto the normalized normal to the plane (in your case (a, b, c)). So:

v = (d, e, f)
        - sum((d, e, f) *. (a, b, c)) * (a, b, c) / sum((a, b, c) *. (a, b, c))

Here, by *. I mean the component-wise product. So this would mean:

sum([x * y for x, y in zip([d, e, f], [a, b, c])])

or

d * a + e * b + f * c

if you just want to be clear but pedantic

and similarly for (a, b, c) *. (a, b, c). Thus, in Python:

from math import sqrt

def dot_product(x, y):
    return sum([x[i] * y[i] for i in range(len(x))])

def norm(x):
    return sqrt(dot_product(x, x))

def normalize(x):
    return [x[i] / norm(x) for i in range(len(x))]

def project_onto_plane(x, n):
    d = dot_product(x, n) / norm(n)
    p = [d * normalize(n)[i] for i in range(len(n))]
    return [x[i] - p[i] for i in range(len(x))]

Then you can say:

p = project_onto_plane([3, 4, 5], [1, 2, 3])
jason
  • 228,647
  • 33
  • 413
  • 517