Python 中的 2D 矢量投影
下面的代码将蓝色向量 AC 投影到红色向量 AB 上,所得投影向量 AD 绘制为紫色。 这是我自己对这个 Wolfram 演示的实现。
然而有些事情是错误的,我真的能弄清楚是什么。 应该是投影公式本身错误或者我将一些局部坐标与世界坐标搞错了。 任何帮助表示赞赏。
这段代码已被修剪,但仍然可以毫无问题地执行,假设您有 pygame:
import pygame
from pygame.locals import *
def vadd(a,b):
return (a[0]+b[0],a[1]+b[1])
def vsub(a,b):
return (a[0]-b[0],a[1]-b[1])
def project(a, b):
""" project a onto b
formula: b(dot(a,b)/(|b|^2))
"""
abdot = (a[0]*b[0])+(a[1]*b[1])
blensq = (b[0]*b[0])+(b[1]*b[1])
temp = float(abdot)/float(blensq)
c = (b[0]*temp,b[1]*temp)
print a,b,abdot,blensq,temp,c
return c
pygame.init()
screen = pygame.display.set_mode((150, 150))
running = True
A = (75.0,75.0)
B = (100.0,50.0)
C = (90,70)
AB = vsub(B,A)
AC = vsub(C,A)
D = project(AC,AB)
AD = vsub(D,A)
while running:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
running = False
pygame.draw.line(screen, (255,0,0), A, B)
pygame.draw.line(screen, (0,0,255), A, C)
pygame.draw.line(screen, (255,0,255), A, D)
pygame.display.flip()
The code below projects the blue vector, AC, onto the red vector, AB, the resulting projected vector, AD, is drawn as purple. This is intended as my own implementation of this Wolfram demonstration.
Something is wrong however and I can really figure out what. Should be either that the projection formula itself is wrong or that I mistake some local coordinates with world coordinates. Any help is appreciated.
This code is trimmed but can still be executed without problems, assuming you have pygame:
import pygame
from pygame.locals import *
def vadd(a,b):
return (a[0]+b[0],a[1]+b[1])
def vsub(a,b):
return (a[0]-b[0],a[1]-b[1])
def project(a, b):
""" project a onto b
formula: b(dot(a,b)/(|b|^2))
"""
abdot = (a[0]*b[0])+(a[1]*b[1])
blensq = (b[0]*b[0])+(b[1]*b[1])
temp = float(abdot)/float(blensq)
c = (b[0]*temp,b[1]*temp)
print a,b,abdot,blensq,temp,c
return c
pygame.init()
screen = pygame.display.set_mode((150, 150))
running = True
A = (75.0,75.0)
B = (100.0,50.0)
C = (90,70)
AB = vsub(B,A)
AC = vsub(C,A)
D = project(AC,AB)
AD = vsub(D,A)
while running:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
running = False
pygame.draw.line(screen, (255,0,0), A, B)
pygame.draw.line(screen, (0,0,255), A, C)
pygame.draw.line(screen, (255,0,255), A, D)
pygame.display.flip()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不应该
是
不幸的是,我无法测试它,但这是我看来唯一错误的事情。
Shouldn't this
be
Unfortunately, I can't test it, but that's the only thing that looks wrong to me.