2
下面的代碼將藍色矢量AC投影到紅色矢量AB上,得到的投影矢量AD繪製爲紫色。這是我自己實現的this Wolfram demonstration。Python中的2D矢量投影
然而,有些事情是錯誤的,我真的可以弄清楚什麼。應該是投影公式本身是錯誤的,或者我錯誤地將一些局部座標與世界座標錯誤。任何幫助表示讚賞。
該代碼被修剪,但仍然可以毫無問題地執行,假設你有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()
通過將D添加到D來定義D並不奏效,因爲尚未定義D。或者我錯過了什麼?你的意思是「D = vadd(A,AD)」? – Mizipzor 2009-07-04 13:27:15