Skip to content

Commit 99f31f9

Browse files
feat: add Pi approximation using Leibniz formula
1 parent 5c39e87 commit 99f31f9

2 files changed

Lines changed: 68 additions & 0 deletions

File tree

‎Maths/PiApproximation.js‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @function leibnizPi
3+
* @description Approximates Pi using the Leibniz formula:
4+
* π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - ...
5+
* @param {number} terms - Number of terms to use in approximation
6+
* @returns {number} - Approximation of Pi
7+
* @see https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80
8+
* @example leibnizPi(1000) => ~3.1405926...
9+
* @example leibnizPi(10000) => ~3.1414926...
10+
*/
11+
const leibnizPi = (terms) => {
12+
if (!Number.isInteger(terms) || terms < 1) {
13+
throw new TypeError('Input must be a positive integer')
14+
}
15+
let sum = 0
16+
for (let i = 0; i < terms; i++) {
17+
sum += (-1) ** i / (2 * i + 1)
18+
}
19+
return 4 * sum
20+
}
21+
22+
export { leibnizPi }

‎Maths/test/PiApproximation.test.js‎

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

0 commit comments

Comments
 (0)