Skip to content

计算模式

a-calc 3.x 引入了计算模式系统,支持三种底层计算引擎的切换,满足不同场景的精度和性能需求。

三种计算模式

模式说明特点适用场景
decimal高精度十进制计算功能最完整,精度高默认模式,通用场景
bigint大整数计算整数运算无精度损失,性能好金融计算、大数运算
wasmWebAssembly 计算高性能,28位精度计算密集型场景

快速开始

js
import { set_config, get_config, calc } from 'a-calc'

// 查看当前模式(默认为 decimal)
get_config('_compute_mode')  // "decimal"

// 切换到 BigInt 模式
set_config({ _compute_mode: 'bigint' })

// 切换到 WASM 模式
set_config({ _compute_mode: 'wasm' })

// 切换回 Decimal 模式
set_config({ _compute_mode: 'decimal' })

使用方式

通过 calc 函数

calc 函数会自动使用当前配置的计算模式:

js
import { calc, set_config } from 'a-calc'

// 默认 decimal 模式
calc('0.1 + 0.2')  // "0.3"
calc('10 / 3 | =5')  // "3.33333"

// 切换到 bigint 模式
set_config({ _compute_mode: 'bigint' })
calc('0.1 + 0.2')  // "0.3"
calc('12345678901234567890 * 2')  // "24691357802469135780"

通过 r* 前缀函数

r* 前缀函数会根据当前模式自动切换底层实现:

js
import { radd, rmul, rdiv, set_config } from 'a-calc'

// 默认 decimal 模式
radd("0.1", "0.2")  // "0.3"
rmul("0.1", "0.2")  // "0.02"
rdiv("1", "3")      // "0.33333333333333333333"

// 切换到 bigint 模式
set_config({ _compute_mode: 'bigint' })
radd("0.1", "0.2")  // "0.3"(结果一致)
rmul("12345678901234567890", "2")  // "24691357802469135780"

设计优势

无论使用哪种模式,调用方式完全相同。只需要在初始化时选择模式,其余代码无需修改。

Decimal 模式(默认)

高精度十进制计算模式。

特点

  • 支持所有运算符和数学函数
  • 精度可配置(默认 50 位)
  • 功能最完整

支持的运算

  • 基础运算:加、减、乘、除、取模、幂、整除
  • 一元运算:abs, neg, sqrt, cbrt
  • 指数对数:exp, ln, log, log2, log10
  • 三角函数:sin, cos, tan, asin, acos, atan
  • 双曲函数:sinh, cosh, tanh, asinh, acosh, atanh
  • 取整运算:floor, ceil, trunc, round
  • 比较运算:max, min, compare, eq, lt, gt, lte, gte
js
import { calc, set_config } from 'a-calc'

set_config({ _compute_mode: 'decimal' })

calc('sqrt(2)')           // "1.4142135623730950488..."
calc('sin(0)')            // "0"
calc('cos(0)')            // "1"
calc('ln(2.718281828)')   // "0.9999999998..."
calc('exp(1)')            // "2.718281828..."

BigInt 模式

使用大整数 + 动态 scale 实现定点数计算。

特点

  • 整数运算完全精确,无精度损失
  • 性能优于 Decimal 模式
  • 支持任意大的整数
  • 不支持无理数运算(自动降级到 Decimal)

核心原理

0.1 + 0.2 的计算过程:
1. 检测小数位数:0.1 → 1位,0.2 → 1位
2. 确定 scale:10^1 = 10
3. 转换为整数:0.1 → 1,0.2 → 2
4. 整数计算:1 + 2 = 3
5. 转回小数:3 / 10 = 0.3

支持的运算(原生实现):

运算符说明精度
加法加法无损
减法减法无损
乘法乘法无损
除法除法_div_precision 控制
取模取模无损
幂运算幂运算整数指数无损
整除整除无损
abs绝对值无损
neg取负无损
floor向下取整无损
ceil向上取整无损
trunc截断取整无损
round四舍五入无损
max, min最大/最小值无损
比较运算比较无损

不支持的运算(自动使用 Decimal 兜底):

js
set_config({ _compute_mode: 'bigint' })

// 这些运算自动使用 Decimal 计算
calc('sqrt(16)')    // "4"
calc('sin(0)')      // "0"
calc('ln(2.718)')   // "0.999..."

大数计算示例

js
set_config({ _compute_mode: 'bigint' })

// 大整数计算,完全精确
calc('12345678901234567890 * 98765432109876543210')
// "1219326311370217952237463801111263526900"

// 科学计数法支持
calc('1.5e-10 + 2.5e-10')  // "0.0000000004"

除法精度配置

BigInt 除法结果可能是无限小数,需要配置精度:

js
import { calc, set_config, get_config } from 'a-calc'

set_config({ _compute_mode: 'bigint' })

// 查看默认精度
get_config('_div_precision')  // 20

// 默认精度下
calc('1 / 3')  // "0.33333333333333333333"(20位小数)

// 修改精度
set_config({ _div_precision: 10 })
calc('1 / 3')  // "0.3333333333"(10位小数)

// 恢复默认
set_config({ _div_precision: 20 })

WASM 模式

使用 WebAssembly 进行高性能计算。

特点

  • 高性能
  • 28-29 位有效数字精度
  • 异步加载,加载前自动使用 Decimal 兜底
  • 支持复杂表达式一次传递计算

加载 WASM 模块

js
import {
  load_wasm,
  is_wasm_loaded,
  set_config,
  calc
} from 'a-calc'

// 异步加载 WASM 模块
await load_wasm()

// 检查是否加载成功
is_wasm_loaded()  // true

// 切换到 WASM 模式
set_config({ _compute_mode: 'wasm' })

// 现在使用 WASM 进行计算
calc('0.1 + 0.2')  // "0.3"

注意

WASM 模块需要异步加载。在加载完成前,即使设置了 wasm 模式,也会自动使用 Decimal 方法兜底,确保计算正常进行。

WASM 表达式计算

WASM 模式提供了 wcalc 函数,可以一次性传递复杂表达式:

js
import { load_wasm, wcalc, set_config } from 'a-calc'

await load_wasm()

// 复杂表达式计算
wcalc("1 + 2 * 3")              // "7"
wcalc("sqrt(16) + pow(2, 3)")   // "12"
wcalc("sin(0) + cos(0)")        // "1"
wcalc("(1 + 2) * (3 + 4)")      // "21"

// 错误处理:通过 _error 配置
set_config({ _error: null })
wcalc("1 / 0")  // null(不抛异常)

支持的运算

类别运算符
基础运算加、减、乘、除、取模、幂、整除
一元运算abs, neg, sqrt, ln, exp, log10
三角函数sin, cos, tan
取整floor, ceil, trunc, round
比较max, min, compare, eq, lt, gt, lte, gte

不支持的运算(使用 Decimal 兜底):

  • cbrt(立方根)
  • log(任意底对数)
  • log2(二进制对数)
  • asin, acos, atan(反三角函数)
  • sinh, cosh, tanh, asinh, acosh, atanh(双曲函数)

兜底机制

a-calc 实现了完善的兜底机制,确保任何情况下计算都能正常进行:

1. 运算符兜底

BigInt 和 WASM 模式中不支持的运算符,自动使用 Decimal 方法:

js
set_config({ _compute_mode: 'bigint' })

// sqrt 在 BigInt 中不支持,自动使用 Decimal
calc('sqrt(16)')  // "4"

// 基础运算使用 BigInt
calc('0.1 + 0.2')  // "0.3"

2. WASM 加载兜底

WASM 加载完成前,自动使用 Decimal:

js
set_config({ _compute_mode: 'wasm' })  // 设置为 WASM 模式

// WASM 尚未加载,自动使用 Decimal
calc('0.1 + 0.2')  // "0.3"

// 加载 WASM
await load_wasm()

// 现在使用真正的 WASM
calc('0.1 + 0.2')  // "0.3"

3. 错误兜底

除零等错误统一处理:

js
import { calc, set_config } from 'a-calc'

// 设置错误返回值
set_config({ _error: 'ERROR' })

calc('1 / 0')  // "ERROR"

// 不设置则抛出异常
set_config({ _error: undefined })
calc('1 / 0')  // throws Error: Division by zero

模式选择指南

场景推荐模式原因
通用计算decimal功能完整,精度高
金融计算bigint整数运算无精度损失
大数运算bigint支持任意大整数
科学计算decimal支持所有数学函数
性能敏感wasm性能优异
前端轻量级bigint无额外依赖

配置参考

js
import { set_config } from 'a-calc'

// 设置计算模式
set_config({ _compute_mode: 'bigint' })

// 设置除法精度(仅影响 bigint 模式)
set_config({ _div_precision: 20 })

// 设置错误返回值
set_config({ _error: '-' })

// 同时设置多个
set_config({
  _compute_mode: 'bigint',
  _div_precision: 30,
  _error: 'N/A'
})

运算符完整对比表

运算符decimalbigintwasm说明
基础运算
加法加法
减法减法
乘法乘法
除法除法
取模取模
幂运算幂运算
整除整除
一元运算
abs绝对值
neg取负
sqrt🔄平方根
cbrt🔄🔄立方根
指数对数
exp🔄e^x
ln🔄自然对数
log10🔄常用对数
log🔄🔄任意底对数
log2🔄🔄二进制对数
三角函数
sin🔄正弦
cos🔄余弦
tan🔄正切
asin🔄🔄反正弦
acos🔄🔄反余弦
atan🔄🔄反正切
双曲函数
sinh🔄🔄双曲正弦
cosh🔄🔄双曲余弦
tanh🔄🔄双曲正切
asinh🔄🔄反双曲正弦
acosh🔄🔄反双曲余弦
atanh🔄🔄反双曲正切
取整运算
floor向下取整
ceil向上取整
trunc截断取整
round四舍五入
比较运算
max最大值
min最小值
compare比较
eq相等
lt小于
gt大于
lte小于等于
gte大于等于

图例

  • ✅ 原生支持
  • 🔄 使用 Decimal 兜底

基于 MIT 许可发布