我正在制作一个制作形状之类的程序。我想通过查找面上存在的每个向量点的平均值来找到面的中心(由3d向量点列表提供)。 以下是我尝试过的:
import math
class vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class plane:
def __init__(self, pointsList):
self.vertex = []
# check that each point is unique
for p in range(0, len(pointsList)-1):
for i in range(p+1, len(pointsList)):
if (pointsList[p] != pointsList[i]):
if (i == len(pointsList)-1):
self.vertex.append(pointsList[p])
else:
return None
self.vertex.append(pointsList[-1])
#returns the mean of x, y, and z
def center(self):
xs = 0
ys = 0
zs = 0
count = len(self.vertex)
for i in range(0, count):
xs += self.vertex[i].x
ys += self.vertex[i].y
zs += self.vertex[i].z
xMean = xs/count
yMean = ys/count
zMean = zs/count
return vector(xMean, yMean, zMean)
然后我去测试函数平面。center():
#initialize some vectors
A = vector(1,7,5)
B = vector(3,9,4)
C = vector(0,1,0)
D = vector(0,0,0)
testList = [A, B, C, D]
#initialize a plane with those vectors
plane1 = plane(testList)
acenter = plane1.center()
print('%d %d %d' % (acenter.x, acenter.y, acenter.z))
然后返回的结果是1 4 2.
我想要x分量、y分量和z分量的平均值,但是4
显然不是7, 9, 1, and 0
的平均值。预期结果应该是1.0, 4.25, 2.25
。我怎样才能做到这一点
谢谢大家。是的,我现在看到错误了。这件事很简单,我觉得很傻。我认为这与我的解释器默认使用python 2有关,但这显然远远不够
即使你自己解决了你的问题,我也会在这里付出我的两分钱。您可以使用Python的内置
dataclass
来构造vector
。这将确保您不必制定手工规则来检查列表中的所有vectors
是否唯一。您可以直接使用set
函数来确保没有重复的向量(我已经重构了变量名以符合PEP8)现在让我们构建
Plane
类:现在让我们看看他们的行动:
这将为您提供:
相关问题 更多 >
编程相关推荐