# 语法¶

## 内核¶

```@ti.kernel
def print_xy(x: ti.i32, y: ti.f32):
print(x + y)
```

```@ti.kernel
def add_xy(x: ti.f32, y: ti.f32) -> ti.i32:
return x + y  # 等价于： ti.cast(x + y, ti.i32)

print(res)  # 3，因为返回值类型是 ti.i32
```

```@ti.kernel
return ti.Matrix([[1, 0], [0, 1]])  # 错误

@ti.kernel
x = 1
y = 0.5
return x, y  # 错误
```

## 函数¶

```@ti.func
def laplacian(t, i, j):
return inv_dx2 * (
-4 * p[t, i, j] + p[t, i, j - 1] + p[t, i, j + 1] + p[t, i + 1, j] +
p[t, i - 1, j])

@ti.kernel
def fdtd(t: ti.i32):
for i in range(n_grid): # 并行
for j in range(n_grid): # 在每个并行的线程中分别顺序执行
laplacian_p = laplacian(t - 2, i, j)
laplacian_q = laplacian(t - 1, i, j)
p[t, i, j] = 2 * p[t - 1, i, j] + (
c * c * dt * dt + c * alpha * dt) * laplacian_q - p[
t - 2, i, j] - c * alpha * dt * laplacian_p
```

```# 错误示范 - 两个返回语句
@ti.func
def safe_sqrt(x):
if x >= 0:
return ti.sqrt(x)
else:
return 0.0

# 正确示范 - 一个返回语句
@ti.func
def safe_sqrt(x):
rst = 0.0
if x >= 0:
rst = ti.sqrt(x)
else:
rst = 0.0
return rst
```

Unlike functions, kernels do not support vectors or matrices as arguments:

```@ti.func
def sdf(u):  # functions support matrices and vectors as arguments. No type-hints needed.
return u.norm() - 1

@ti.kernel
def render(d_x: ti.f32, d_y: ti.f32):  # kernels do not support vector/matrix arguments yet. We have to use a workaround.
d = ti.Vector([d_x, d_y])
p = ti.Vector([0.0, 0.0])
t = sdf(p)
p += d * t
...
```

## 标量算术¶

Taichi 支持的标量函数：

`ti.``sin`(x)
`ti.``cos`(x)
`ti.``asin`(x)
`ti.``acos`(x)
`ti.``atan2`(x, y)
`ti.``cast`(x, data_type)
`ti.``sqrt`(x)
`ti.``rsqrt`(x)
`ti.``floor`(x)
`ti.``ceil`(x)
`ti.``tan`(x)
`ti.``tanh`(x)
`ti.``exp`(x)
`ti.``log`(x)
`ti.``random`(data_type)
`abs`(x)
`int`(x)
`float`(x)
`max`(x, y)
`min`(x, y)
`pow`(x, y)

Python 3 中 `/` （浮点数除法）和 `//` （整数除法）是区分开来的。例如，`1.0 / 2.0 = 0.5``1 / 2 = 0.5``1 // 2 = 0``4.2 // 2 = 2`。Taichi 也遵循了这个设计：

• true divisions on integral types will first cast their operands to the default float point type.
• floor divisions on float-point types will first cast their operands to the default integer type.

```B = ti.Matrix([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
C = ti.Matrix([[3.0, 4.0, 5.0], [6.0, 7.0, 8.0]])

A = ti.sin(B)
# is equivalent to
for i in ti.static(range(2)):
for j in ti.static(range(3)):
A[i, j] = ti.sin(B[i, j])

A = ti.pow(B, 2)
# is equivalent to
for i in ti.static(range(2)):
for j in ti.static(range(3)):
A[i, j] = ti.pow(B[i, j], 2)

A = ti.pow(B, C)
# is equivalent to
for i in ti.static(range(2)):
for j in ti.static(range(3)):
A[i, j] = ti.pow(B[i, j], C[i, j])

A += 2
# is equivalent to
for i in ti.static(range(2)):
for j in ti.static(range(3)):
A[i, j] += 2

A += B
# is equivalent to
for i in ti.static(range(2)):
for j in ti.static(range(3)):
A[i, j] += B[i, j]
```