向量¶
在Taichi中,向量的表述有两种形式:
- 作为临时局部变量,一个
n
分量的向量由标量n
组成。- 作为全局张量(global tensor)的构成元素。比如,由向量
n
组成的N-维数组构成了的一个全局张量。
In fact, Vector
is simply an alias of Matrix
, just with m = 1
. See Matrices and 张量与矩阵 for more details.
声明向量¶
全局张量中的向量¶
-
ti.Vector.
var
(n, dt, shape = None, offset = None)¶ 参数: - n – (标量) 向量中分量数目
- dt – (数据类型) 向量中分量的数据类型
- shape – (optional, scalar or tuple) shape the tensor of vectors, see 张量与矩阵
- offset – (optional, scalar or tuple) see Coordinate offsets
例如, 这里我们创建了一个5x4的张量,张量中的元素都是3维的向量:
# Python-scope a = ti.Vector.var(3, dt=ti.f32, shape=(5, 4))
注解
在Python-scope中, ti.var
声明 Tensors of scalars, 而 ti.Vector
声明了由向量构成的张量。
访问向量分量¶
全局张量中的向量¶
-
a[p, q, ...][i]
参数: - a – (tensor of Vector) the vector
- p – (标量) 张量的行索引
- q – (标量) 张量的列索引
- i – (标量) 向量内分量的索引
这里提取出了向量
a[6, 3]
的第一个分量:x = a[6, 3][0] # or vec = a[6, 3] x = vec[0]
注解
Always use two pairs of square brackets to access scalar elements from tensors of vectors.
- 第一组方括号负责定位张量中的向量;
- 第二组方括号负责定位向量中的标量。
特别的,对0维张量第一组方括号应该使用 [None]
。
临时局部变量向量¶
-
a[i]
参数: - a – (向量)
- i – 指定访问下标
例如,这里我们提取出了向量
a
的第一个分量:x = a[0]
同理,将
a
的第二个分量设置为 4:a[1] = 4
TODO: add descriptions about
a(i, j)
相关方法¶
-
a.
norm
(eps = 0)¶ 参数: - a – (向量)向量
- eps – (可选标量) sqrt的安全保护值,通常为0. 详见下面注解。
返回: (标量) 向量的大小、长度、范数
例如:
a = ti.Vector([3, 4]) a.norm() # sqrt(3*3 + 4*4 + 0) = 5
a.norm(eps)
相当于ti.sqrt(a.dot(a) + eps)
注解
可以通过设置 eps = 1e-5
,对可微分编程中零向量上的梯度值计算进行防护。
-
a.
norm_sqr
()¶ 参数: a – (向量)向量 返回: (scalar) the square of the magnitude / length / norm of vector 例如:
a = ti.Vector([3, 4]) a.norm_sqr() # 3*3 + 4*4 = 25
a.norm_sqr()
is equivalent toa.dot(a)
-
a.
normalized
()¶ 参数: a – (向量)向量 返回: (Vector) the normalized / unit vector of a
例如:
a = ti.Vector([3, 4]) a.normalized() # [3 / 5, 4 / 5]
a.normalized()
is equivalent toa / a.norm()
.
-
a.
dot
(b)¶ 参数: - a – (向量)向量
- b – (向量)向量
返回: (标量)
a
和b
之间点乘(内积)的结果例如:
a = ti.Vector([1, 3]) b = ti.Vector([2, 4]) a.dot(b) # 1*2 + 3*4 = 14
-
a.
cross
(b)¶ 参数: - a – (Vector, 2 or 3 components)
- b – (Vector of the same size as a)
返回: (scalar (for 2D inputs), or 3D Vector (for 3D inputs)) the cross product of
a
andb
We use a right-handed coordinate system. E.g.,
a = ti.Vector([1, 2, 3]) b = ti.Vector([4, 5, 6]) c = ti.cross(a, b) # c = [2*6 - 5*3, 4*3 - 1*6, 1*5 - 4*2] = [-3, 6, -3] p = ti.Vector([1, 2]) q = ti.Vector([4, 5]) r = ti.cross(a, b) # r = 1*5 - 4*2 = -3
-
a.
outer_product
(b)¶ 参数: - a – (向量)向量
- b – (向量)向量
返回: (矩阵)
a
和b
之间张量积的结果例如:
a = ti.Vector([1, 2]) b = ti.Vector([4, 5, 6]) c = ti.outer_product(a, b) # NOTE: c[i, j] = a[i] * b[j] # c = [[1*4, 1*5, 1*6], [2*4, 2*5, 2*6]]
注解
This have no common with ti.cross
. a
and b
do not have to be 3 or 2 component vectors.
-
a.
cast
(dt)¶ 参数: - a – (向量)向量
- dt – (DataType)
返回: (向量) 将向量
a
中分量的数据类型转化为类型dt
例如:
# Taichi-scope a = ti.Vector([1.6, 2.3]) a.cast(ti.i32) # [2, 3]
注解
向量是只有一列的特殊矩阵。实际上,ti.Vector
只是 ti.Matrix
的别名。