forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add an algorithm to find Taylor series approximation of exponential f… (
- Loading branch information
1 parent
5867186
commit 73bf91d
Showing
2 changed files
with
41 additions
and
0 deletions.
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,25 @@ | ||
/** | ||
* @function exponentialFunction | ||
* @description Calculates the n+1 th order Taylor series approximation of exponential function e^x given n | ||
* @param {Integer} power | ||
* @param {Integer} order - 1 | ||
* @returns exponentialFunction(2,20) = 7.3890560989301735 | ||
* @url https://en.wikipedia.org/wiki/Exponential_function | ||
*/ | ||
function exponentialFunction (power, n) { | ||
let output = 0 | ||
let fac = 1 | ||
if (isNaN(power) || isNaN(n) || n < 0) { | ||
throw new TypeError('Invalid Input') | ||
} | ||
if (n === 0) { return 1 } | ||
for (let i = 0; i < n; i++) { | ||
output += (power ** i) / fac | ||
fac *= (i + 1) | ||
} | ||
return output | ||
} | ||
|
||
export { | ||
exponentialFunction | ||
} |
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,16 @@ | ||
import { exponentialFunction } from '../ExponentialFunction' | ||
|
||
describe('Tests for exponential function', () => { | ||
it('should be a function', () => { | ||
expect(typeof exponentialFunction).toEqual('function') | ||
}) | ||
|
||
it('should throw error for invalid input', () => { | ||
expect(() => exponentialFunction(2, -34)).toThrow() | ||
}) | ||
|
||
it('should return the exponential function of power of 5 and order of 21', () => { | ||
const ex = exponentialFunction(5, 20) | ||
expect(ex).toBe(148.4131078683383) | ||
}) | ||
}) |