node-math
v1.1.1
Published
node-math is a lightweight mathematical utility library that provides a rich set of mathematical functions and constants. It is suitable for scientific computing, engineering applications, and mathematical needs in daily development, supporting both Commo
Readme
node-math
node-math 是一个轻量级的数学工具库,提供了丰富的数学函数和常量,适用于科学计算、工程应用以及日常开发中的数学需求,支持 CommonJS、ES Module。
功能特性
基础数学运算
- 平方根:
sqrt(x)- 计算非负数的平方根。 - 取整:
ceil(x)- 向上取整。floor(x)- 向下取整。round(x)- 四舍五入。
- 绝对值:
abs(x)- 返回数字的绝对值。 - 符号函数:
sign(x)- 判断数字的正负性。 - 范围限制:
clamp(x, min, max)- 将数字限制在指定范围内。 - 整数判断:
isInteger(x)- 判断是否为整数。 - 有限数判断:
isFiniteNumber(x)- 判断是否为有限数。
数学常量
e- 欧拉常数(约等于 2.71828)。pi- 圆周率 π(约等于 3.14159)。tau- Tau 常数 τ(等于 2π,约等于 6.28318)。inf- 正无穷大。nan- 非数字值。
指数与对数
- 指数函数:
exp(x)- 计算 e 的 x 次幂。pow(x, y)- 计算 x 的 y 次幂。
- 对数函数:
log(x, base)- 计算以指定底数为基准的对数值。log10(x)- 计算以 10 为底的对数值。
- 指数增长/衰减:
exponentialGrowth(A, k, t)- 计算指数增长或衰减值。
数论相关
- 最大公约数:
gcd(a, b)- 使用欧几里得算法计算两个数的最大公约数。 - 最小公倍数:
lcm(a, b)- 计算两个数的最小公倍数。 - 阶乘:
factorial(x)- 计算非负整数的阶乘。 - 素数判断:
isPrime(n)- 判断一个数是否为素数。 - 素数生成:
sieveOfEratosthenes(n)- 使用埃拉托色尼筛法生成小于等于 n 的所有素数。 - 组合与排列:
comb(n, k)- 计算组合数 C(n, k)。perm(n, k)- 计算排列数 P(n, k)。
三角函数
- 基本三角函数:
sin(x)- 正弦值。cos(x)- 余弦值。tan(x)- 正切值。
- 反三角函数:
asin(x)- 反正弦值。acos(x)- 反余弦值。atan(x)- 反正切值。
- 角度转换:
toRadians(degrees)- 将角度转换为弧度。toDegrees(radians)- 将弧度转换为角度。
- 双曲函数:
sinh(x)- 双曲正弦。cosh(x)- 双曲余弦。tanh(x)- 双曲正切。
- 反双曲函数:
asinh(x)- 反双曲正弦。acosh(x)- 反双曲余弦。atanh(x)- 反双曲正切。
安装与使用
安装方式
1. 直接克隆仓库
git clone https://gitee.com/nodets/node-math.git
cd node-math
npm install
npm run build # 生成各环境适配版本2. NPM 安装(未来支持)
npm install @nodets/node-math
# 或
yarn add @nodets/node-math环境支持与使用示例
1. ES Module (ESM) 环境
适用于现代 Node.js (v14+)、TypeScript 项目或支持 ESM 的浏览器打包工具(Webpack/Vite)
// 导入全部内容
import * as math from 'node-math/dist/esm/index.js';
// 按需导入
import { sqrt, pi, factorial, gcd } from 'node-math/dist/esm/index.js';
console.log(sqrt(16)); // 输出 4
console.log(pi); // 输出 3.141592653589793
console.log(factorial(5)); // 输出 120
console.log(gcd(56, 98)); // 输出 142. CommonJS 环境
适用于传统 Node.js 项目(使用 require)
// 导入全部内容
const math = require('node-math/dist/cjs/index.js');
// 按需导入
const { sqrt, pi, factorial, gcd } = require('node-math/dist/cjs/index.js');
console.log(sqrt(25)); // 输出 5
console.log(math.toDegrees(math.pi / 2)); // 输出 903. 浏览器环境
可直接通过 <script> 标签引入 UMD 格式文件,库会暴露为全局变量 nodeMath
<!-- 本地引入 -->
<script src="node-math/dist/umd/node-math.min.js"></script>
<!-- 或使用 CDN(未来支持) -->
<script src="https://cdn.example.com/node-math/latest/node-math.min.js"></script>
<script>
// 使用全局变量 nodeMath
console.log(nodeMath.sqrt(36)); // 输出 6
console.log(nodeMath.sin(nodeMath.toRadians(30))); // 输出 0.5
console.log(nodeMath.factorial(6)); // 输出 720
</script>4. TypeScript 项目
库内置类型定义,可直接获得类型提示
import { isPrime, comb } from 'node-math/dist/esm/index.js';
// 类型提示会自动生效
const primeCheck = isPrime(17); // boolean 类型
const combination = comb(10, 3); // number 类型许可证
本项目采用 MIT 许可证开源,详情参见 LICENSE 文件。
