gpt4 book ai didi

python - 叉积 3D 空间中的所有点

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:43 25 4
gpt4 key购买 nike

我有一个向量,a,我希望它与定义的 3D 空间中的每个点相交。

import numpy as np

# Grid
x = np.arange(-4,4,0.1)
y = np.arange(-4,4,0.1)
z = np.arange(-4,4,0.1)

a = [1,0,0]

result = [[] for i in range(3)]

for j in range(len(x)): # loop on x coords
for k in range(len(y)): # loop on y coords
for l in range(len(z)): # loop on z coords
r = [x[j] , y[k], z[l]]
result[0].append(np.cross(a, r)[0])
result[1].append(np.cross(a, r)[1])
result[2].append(np.cross(a, r)[2])

这会生成一个数组,该数组采用了 a 与空间中每个点的叉积。但是,由于嵌套循环,该过程花费的时间太长。有没有办法利用向量(也许是网状网格?)来加快这个过程?

最佳答案

这是一种矢量化方法 -

np.cross(a, np.array(np.meshgrid(x,y,z)).transpose(2,1,3,0)).reshape(-1,3).T

sample 运行-

In [403]: x = np.random.rand(4)
...: y = np.random.rand(5)
...: z = np.random.rand(6)
...:

In [404]: result = original_app(x,y,z,a)

In [405]: out = np.cross(a, np.array(np.meshgrid(x,y,z)).\
transpose(2,1,3,0)).reshape(-1,3).T

In [406]: np.allclose(result[0], out[0])
Out[406]: True

In [407]: np.allclose(result[1], out[1])
Out[407]: True

In [408]: np.allclose(result[2], out[2])
Out[408]: True

运行时测试-

# Original setup used in the question
In [393]: # Grid
...: x = np.arange(-4,4,0.1)
...: y = np.arange(-4,4,0.1)
...: z = np.arange(-4,4,0.1)
...:

# Original approach
In [397]: %timeit original_app(x,y,z,a)
1 loops, best of 3: 21.5 s per loop

# @Denziloe's soln
In [395]: %timeit [np.cross(a, r) for r in product(x, y, z)]
1 loops, best of 3: 7.34 s per loop

# Proposed in this post
In [396]: %timeit np.cross(a, np.array(np.meshgrid(x,y,z)).\
transpose(2,1,3,0)).reshape(-1,3).T
100 loops, best of 3: 16 ms per loop

超过 1000x 比原来的加速超过 450x 来自其他帖子的循环方法.

关于python - 叉积 3D 空间中的所有点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42786781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com