From 73bf91d7e153b07bade0543203c1d452affd8251 Mon Sep 17 00:00:00 2001 From: Prashal Ruchiranga <98536996+prashalruchiranga@users.noreply.github.com> Date: Thu, 20 Oct 2022 17:10:22 +0530 Subject: [PATCH] =?UTF-8?q?Add=20an=20algorithm=20to=20find=20Taylor=20ser?= =?UTF-8?q?ies=20approximation=20of=20exponential=20f=E2=80=A6=20(#1160)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Maths/ExponentialFunction.js | 25 +++++++++++++++++++++++++ Maths/test/ExponentialFunction.test.js | 16 ++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 Maths/ExponentialFunction.js create mode 100644 Maths/test/ExponentialFunction.test.js diff --git a/Maths/ExponentialFunction.js b/Maths/ExponentialFunction.js new file mode 100644 index 0000000000..4212693810 --- /dev/null +++ b/Maths/ExponentialFunction.js @@ -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 +} diff --git a/Maths/test/ExponentialFunction.test.js b/Maths/test/ExponentialFunction.test.js new file mode 100644 index 0000000000..d1eed4895f --- /dev/null +++ b/Maths/test/ExponentialFunction.test.js @@ -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) + }) +})