-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: ♻️ move derivative from ootk-core
- Loading branch information
Showing
3 changed files
with
28 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
export * from './jacobian'; | ||
export * from './functions'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
}); |