js实现求导
实现数值微分的方法
在JavaScript中实现求导通常采用数值微分方法,因为JavaScript本身不提供符号计算能力。以下是几种常见的数值微分实现方式:
前向差分法
用函数在某点的函数值及其邻近点的函数值近似计算导数:

function derivative(f, x, h = 1e-5) {
return (f(x + h) - f(x)) / h;
}
中心差分法
更精确的二阶近似方法:
function derivative(f, x, h = 1e-5) {
return (f(x + h) - f(x - h)) / (2 * h);
}
高阶导数计算
通过递归方式计算高阶导数:

function nthDerivative(f, x, n, h = 1e-4) {
if (n === 0) return f(x);
const df = (f(x + h) - f(x - h)) / (2 * h);
return nthDerivative(x => (f(x + h) - f(x - h)) / (2 * h), x, n - 1, h);
}
自动微分实现
对于需要更精确微分的情况,可以构建简单的自动微分系统:
class AutoDiff {
constructor(value, derivative = 0) {
this.value = value;
this.derivative = derivative;
}
add(b) {
const value = this.value + b.value;
const derivative = this.derivative + b.derivative;
return new AutoDiff(value, derivative);
}
mul(b) {
const value = this.value * b.value;
const derivative = this.derivative * b.value + this.value * b.derivative;
return new AutoDiff(value, derivative);
}
}
// 示例:计算f(x) = x^2在x=3处的导数
const x = new AutoDiff(3, 1); // 初始导数设为1
const y = x.mul(x); // y = x * x
console.log(y.derivative); // 输出6
符号微分库
对于复杂需求,可以使用现有库如:
- math.js:提供符号计算和微分功能
- algebra.js:支持符号运算
- numeric.js:专注于数值计算
// 使用math.js示例
const math = require('mathjs');
const expr = math.parse('x^2 + sin(x)');
const derivative = math.derivative(expr, 'x').toString();
console.log(derivative); // 输出"2 * x + cos(x)"
注意事项
- 数值微分中的步长h选择很重要,太小会引入舍入误差,太大会增加截断误差
- 对于不连续或剧烈变化的函数,数值微分可能不准确
- 自动微分和符号微分更适合复杂函数的精确求导
以上方法可根据具体需求选择使用,数值微分适合简单快速计算,自动微分和符号微分适合需要精确结果的场景。






