Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding sum of sequence upto a specified accuracy using JavaScript
We need to find the sum of a sequence where each term is the reciprocal of factorials. The sequence is: 1/1, 1/2, 1/6, 1/24, ... where the nth term is 1/n!.
Understanding the Sequence
The sequence can be written as:
- 1st term: 1/1! = 1/1 = 1
- 2nd term: 1/2! = 1/2 = 0.5
- 3rd term: 1/3! = 1/6 ? 0.167
- 4th term: 1/4! = 1/24 ? 0.042
Each term is 1 divided by the factorial of its position number.
Mathematical Formula
Sum = 1/1! + 1/2! + 1/3! + ... + 1/n!
Implementation
const num = 5;
const seriesSum = (n = 1) => {
let sum = 0;
let factorial = 1;
for (let i = 1; i <= n; i++) {
factorial = factorial * i; // Calculate i!
sum += 1 / factorial; // Add 1/i! to sum
}
return sum;
};
console.log("Sum of first", num, "terms:", seriesSum(num));
// Let's see individual terms
for (let i = 1; i <= num; i++) {
let fact = 1;
for (let j = 1; j <= i; j++) {
fact *= j;
}
console.log(`Term ${i}: 1/${fact} = ${(1/fact).toFixed(6)}`);
}
Sum of first 5 terms: 1.7166666666666666 Term 1: 1/1 = 1.000000 Term 2: 1/2 = 0.500000 Term 3: 1/6 = 0.166667 Term 4: 1/24 = 0.041667 Term 5: 1/120 = 0.008333
Optimized Version with Accuracy Control
For better precision control, we can stop when terms become negligibly small:
const seriesSumWithAccuracy = (maxTerms = 10, accuracy = 0.000001) => {
let sum = 0;
let factorial = 1;
let term;
for (let i = 1; i <= maxTerms; i++) {
factorial = factorial * i;
term = 1 / factorial;
sum += term;
console.log(`Term ${i}: ${term.toFixed(8)}, Running sum: ${sum.toFixed(8)}`);
// Stop if term is smaller than required accuracy
if (term < accuracy) {
console.log(`Stopped at term ${i} (accuracy reached)`);
break;
}
}
return sum;
};
console.log("\nFinal sum:", seriesSumWithAccuracy(10, 0.0001));
Term 1: 1.00000000, Running sum: 1.00000000 Term 2: 0.50000000, Running sum: 1.50000000 Term 3: 0.16666667, Running sum: 1.66666667 Term 4: 0.04166667, Running sum: 1.70833333 Term 5: 0.00833333, Running sum: 1.71666667 Term 6: 0.00138889, Running sum: 1.71805556 Term 7: 0.00019841, Running sum: 1.71825397 Stopped at term 7 (accuracy reached) Final sum: 1.7182539682539683
Mathematical Significance
This series converges to e - 1 ? 1.71828, where e is Euler's number (? 2.71828). The series 1 + 1/1! + 1/2! + 1/3! + ... equals e.
Conclusion
The sum of reciprocals of factorials converges quickly to e - 1. Using accuracy control helps determine when sufficient precision is achieved without unnecessary computation.
Advertisements
