Skip to content

Commit 418ac6b

Browse files
make exponentialFunction iterative using a for loop
1 parent 7b4ff6e commit 418ac6b

File tree

2 files changed

+9
-8
lines changed

2 files changed

+9
-8
lines changed

Maths/ExponentialFunction.js

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,23 @@
1-
let powerOfX = 1
2-
let factorial = 1
1+
import { calcFactorial } from './Factorial.js'
2+
33
/**
44
* @function exponentialFunction
55
* @description Calculates the n+1 th order Taylor series approximation of exponential function e^x given n
66
* @param {Integer} power
77
* @param {Integer} order - 1
8-
* @returns exponentialFunction(2,20) = 7.389056098930604
8+
* @returns exponentialFunction(2,20) = 7.3890560989301735
99
* @url https://en.wikipedia.org/wiki/Exponential_function
1010
*/
1111
function exponentialFunction (power, n) {
12+
let output = 0
1213
if (isNaN(power) || isNaN(n) || n < 0) {
1314
throw new TypeError('Invalid Input')
1415
}
1516
if (n === 0) { return 1 }
16-
const recursion = exponentialFunction(power, n - 1)
17-
powerOfX = powerOfX * power
18-
factorial = factorial * n
19-
return recursion + powerOfX / factorial
17+
for(let i = 0; i < n; i++){
18+
output += (power ** i) / calcFactorial(i)
19+
}
20+
return output
2021
}
2122

2223
export {

Maths/test/ExponentialFunction.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,6 @@ describe('Tests for exponential function', () => {
1111

1212
it('should return the exponential function of power of 5 and order of 21', () => {
1313
const ex = exponentialFunction(5, 20)
14-
expect(ex).toBe(148.4131470673818)
14+
expect(ex).toBe(148.4131078683383)
1515
})
1616
})

0 commit comments

Comments
 (0)