# 数学
数值标准库函数按使用频率划分,而不是按领域:
日常操作保持为裸的顶层动词,而专门化的函数位于
`math/` 命名空间下。这种划分模仿了 Python 的
builtins 与 `math` 之分工,也让顶层命名空间保持
整洁。所有这些函数都编译进每个运行时且无需导入;
命名理由见
语法与风格。
## 函数
### 裸形式(日常)
| 函数 | 用途 |
|---|---|
| `abs n` | 绝对值 |
| `floor n`, `ceil n`, `round n` | 向下、向上或四舍五入到最近整数 |
| `min a b ...`, `max a b ...` | 参数的最小值 / 最大值,或单个列表的最小/最大值 |
| `clamp n lo hi` | 将值限制在区间 `[lo, hi]` |
| `random` | `[0.0, 1.0)` 中的随机浮点数 |
| `mod a b` | `a / b` 的余数(截断除法;符号与被除数一致) |
| `int x` | 强制转换为整数,向零截断;字符串无法解析时为 `nil` |
`random` 不接受参数:`[random]` 返回 `[0.0, 1.0)` 中的浮点数。
要用于其他范围请自行缩放,或使用 `math/random-range` 获得
给定区间内的浮点数。
### `math/`(专门化)
| 函数 | 用途 |
|---|---|
| `math/sqrt n` | 平方根 |
| `math/pow base exp` | `base` 的 `exp` 次幂 |
| `math/sum n ...` / `math/sum $numbers` | 所有参数或单个列表之和;空时为 `0` |
| `math/avg n ...` / `math/avg $numbers` | 算术平均值;空时为 `0` |
| `math/sin x`, `math/cos x`, `math/tan x` | 三角函数(弧度) |
| `math/asin x`, `math/acos x`, `math/atan x` | 反三角函数(弧度) |
| `math/atan2 y x` | 双参数反正切,可感知象限 |
| `math/exp x` | 欧拉数 e 的 `x` 次幂 |
| `math/ln x`, `math/log10 x`, `math/log2 x` | 自然对数、以 10 为底的对数、以 2 为底的对数 |
| `math/sign x` | 按符号返回 `-1`, `0` 或 `1` |
| `math/trunc x` | 向零截断 |
| `math/hypot x y` | `sqrt(x*x + y*y)`,计算时避免不必要的溢出或下溢 |
| `math/lerp a b t` | 线性插值:`a + (b - a) * t` |
| `math/random-range min max` | `[min, max)` 中的随机浮点数 |
| `math/pi` | π——零参数函数,调用 `[math/pi]` |
| `math/euler` | 欧拉数 e——零参数函数,调用 `[math/euler]` |
`math/pi` 和 `math/euler` 是函数而非常量:请写 `[math/pi]`,
绝不要写 `$math/pi` 或裸的 `math/pi` 引用。像其他调用一样
在分组表达式中使用它们:`([math/pi] * [math/pow $r 2])`。
## 示例
# Everyday ops stay bare set qty 3 set price 19.99 set total ($price * $qty) echo "rounded:" [round $total] # 60 echo "clamped:" [clamp $total 0 50] # 50 echo "remainder:" [mod 17 5] # 2 echo "parsed:" [int "42"] # 42 # Specialised ops live under math/ echo "sqrt:" [math/sqrt 9] # 3 echo "hypotenuse:" [math/hypot 3 4] # 5 echo "lerp:" [math/lerp 0 100 0.25] # 25 echo "ranged:" [math/random-range 10 20] set radius 2.5 set area ([math/pi] * [math/pow $radius 2]) echo "area:" [round $area] # 20