Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Maths/PiApproximation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* @function leibnizPi
* @description Approximates Pi using the Leibniz formula:
* π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - ...
* @param {number} terms - Number of terms to use in approximation
* @returns {number} - Approximation of Pi
* @see https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80
* @example leibnizPi(1000) => ~3.1405926...
* @example leibnizPi(10000) => ~3.1414926...
*/
const leibnizPi = (terms) => {
if (!Number.isInteger(terms) || terms < 1) {
throw new TypeError('Input must be a positive integer')
}
let sum = 0
for (let i = 0; i < terms; i++) {
sum += (-1) ** i / (2 * i + 1)
}
return 4 * sum
}

export { leibnizPi }
46 changes: 46 additions & 0 deletions Maths/test/PiApproximation.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { leibnizPi } from '../PiApproximation.js'

describe('leibnizPi', () => {
test('leibnizPi(1) returns 4', () => {
expect(leibnizPi(1)).toBe(4)
})

test('leibnizPi(2) returns 2.666...', () => {
expect(leibnizPi(2)).toBeCloseTo(2.667, 2)
})

test('leibnizPi(100) approximates pi', () => {
expect(leibnizPi(100)).toBeCloseTo(3.13, 1)
})

test('leibnizPi(1000) approximates pi more closely', () => {
expect(leibnizPi(1000)).toBeCloseTo(3.14, 2)
})

test('leibnizPi(10000) approximates pi even more closely', () => {
expect(leibnizPi(10000)).toBeCloseTo(3.1415, 3)
})

test('more terms give better approximation', () => {
const pi = Math.PI
expect(Math.abs(leibnizPi(10000) - pi)).toBeLessThan(
Math.abs(leibnizPi(100) - pi)
)
})

test('throws TypeError for zero', () => {
expect(() => leibnizPi(0)).toThrow(TypeError)
})

test('throws TypeError for negative input', () => {
expect(() => leibnizPi(-100)).toThrow(TypeError)
})

test('throws TypeError for float input', () => {
expect(() => leibnizPi(100.5)).toThrow(TypeError)
})

test('throws TypeError for string input', () => {
expect(() => leibnizPi('100')).toThrow(TypeError)
})
})
Loading