Skip to content

Commit

Permalink
refactor: ♻️ move derivative from ootk-core
Browse files Browse the repository at this point in the history
  • Loading branch information
thkruz committed Jan 17, 2024
1 parent 2e1faa4 commit 9a9b50d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
21 changes: 21 additions & 0 deletions src/utils/functions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { DifferentiableFunction } from '../main';

/**
* Calculates the derivative of a differentiable function.
* @param f The differentiable function.
* @param h The step size for numerical differentiation. Default value is 1e-3.
* @returns The derivative function.
*/
export function derivative(f: DifferentiableFunction, h = 1e-3): DifferentiableFunction {
/**
* @param x The value at which to calculate the derivative.
* @returns The derivative of the function at the given value.
*/
function df(x: number): number {
const hh = h * 0.5;

return (f(x + hh) - f(x - hh)) / h;
}

return df;
}
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './jacobian';
export * from './functions';
7 changes: 6 additions & 1 deletion test/utils/functions.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { jacobian } from '../../src/main';
import { derivative, jacobian } from '../../src/main';

// jacobian
it('should be calculate jacobian', () => {
expect(jacobian((xs: Float64Array) => xs, 1, new Float64Array([1, 2, 3]))).toMatchSnapshot();
});

// derivative
it('should be calculate derivative', () => {
expect(derivative((x: number) => x * x, 1)).toMatchSnapshot();
});

0 comments on commit 9a9b50d

Please sign in to comment.