Skip to content

Commit 694111d

Browse files
feat: add Euler number approximation algorithm
1 parent 5c39e87 commit 694111d

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

‎Maths/EulerNumber.js‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @function eulerNumber
3+
* @description Approximates Euler's number (e) using the formula:
4+
* e = sum(1/n!) for n from 0 to infinity.
5+
* This function computes e to a specified number of terms.
6+
* @param {number} terms - Number of terms to use in approximation
7+
* @returns {number} - Approximation of Euler's number e
8+
* @see https://en.wikipedia.org/wiki/E_(mathematical_constant)
9+
* @example eulerNumber(10) => 2.7182818011...
10+
* @example eulerNumber(20) => 2.718281828459045
11+
*/
12+
const eulerNumber = (terms) => {
13+
if (!Number.isInteger(terms) || terms < 1) {
14+
throw new TypeError('Input must be a positive integer')
15+
}
16+
let result = 0
17+
let factorial = 1
18+
for (let i = 0; i < terms; i++) {
19+
if (i > 0) factorial *= i
20+
result += 1 / factorial
21+
}
22+
return result
23+
}
24+
25+
export { eulerNumber }

‎Maths/test/EulerNumber.test.js‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { eulerNumber } from '../EulerNumber.js'
2+
3+
describe('eulerNumber', () => {
4+
test('eulerNumber(1) returns 1', () => {
5+
expect(eulerNumber(1)).toBe(1)
6+
})
7+
8+
test('eulerNumber(2) returns 2', () => {
9+
expect(eulerNumber(2)).toBe(2)
10+
})
11+
12+
test('eulerNumber(5) approximates e', () => {
13+
expect(eulerNumber(5)).toBeCloseTo(2.708, 2)
14+
})
15+
16+
test('eulerNumber(10) approximates e closely', () => {
17+
expect(eulerNumber(10)).toBeCloseTo(2.71828, 4)
18+
})
19+
20+
test('eulerNumber(20) approximates e very closely', () => {
21+
expect(eulerNumber(20)).toBeCloseTo(2.718281828459045, 10)
22+
})
23+
24+
test('more terms give better approximation', () => {
25+
const e = Math.E
26+
expect(Math.abs(eulerNumber(20) - e)).toBeLessThan(
27+
Math.abs(eulerNumber(5) - e)
28+
)
29+
})
30+
31+
test('throws TypeError for zero', () => {
32+
expect(() => eulerNumber(0)).toThrow(TypeError)
33+
})
34+
35+
test('throws TypeError for negative input', () => {
36+
expect(() => eulerNumber(-10)).toThrow(TypeError)
37+
})
38+
39+
test('throws TypeError for float input', () => {
40+
expect(() => eulerNumber(10.5)).toThrow(TypeError)
41+
})
42+
43+
test('throws TypeError for string input', () => {
44+
expect(() => eulerNumber('10')).toThrow(TypeError)
45+
})
46+
})

0 commit comments

Comments
 (0)