C Program: Exponential Series

The number $e$ is a famous mathematical constant known as Euler's Number, named after the well-known Swiss mathematician Leonhard Euler.

It is irrational and has the approximate value 2.71828. For a given $x$ in $R$, the exponential function $e^{x}$ or sometimes $\text{exp}(x)$ is given by

$e^{x} = 1 + x + \frac{x^{2}}{2!} + \frac{x^{3}}{3!} + \frac{x^{4}}{4!} + ...$

leonhard euler Leonhard Euler. Public Domain

The series can be derived by applying Maclaurin's Series to the exponential function $e^{x}$.

The exponential series converges for all values of $x$.

We observe the terms of the series and note that since $x^{0} = 1$ and $0! = 1$, the first term, which is $1$, can also be written as $\frac{x^{0}}{0!}$, conforming with rest of the terms in the series. So, each term of the series is actually $\frac{x^{n}}{n!}$, where $n = 0, 1, 2, 3, ...$. For computing the numerator and denominator of each term, we will be needing the power and factorial functions.

The actual summation of the series terms takes place inside the while loop, where the power() and factorial() functions are invoked.

				
				#include <stdio.h>	
				unsigned long factorial(unsigned short int);	
				float power(float, unsigned short int);

				int main() {
					unsigned short n, i = 0;
					float x, sum = 0;

					printf("n: ");
					scanf("%hu", &n);

					printf("x: ");
					scanf("%f", &x);

					while(i < n) {					
						sum += power(x,i)/(float) factorial(i);			
						i++;
					}

					printf("Sum upto %hd terms = %f", n, sum);

					return 0;
				}

				float power(float x, unsigned short n) {
					float pow = 1;

					while(n > 0) { 
						pow *= x;
						--n; 
					}

					return pow;
				}

				unsigned long factorial(unsigned short n) {
					unsigned long f;

					if(n == 0 || n == 1)
						return 1;
					else
						f = n * factorial(n-1);

					return f;
				}
				
			

We will verify our summation values for some trivial values of $x$.

When $x = 0$, it is $e^{0}$, and hence the computed sum should be 1.

When $x = 1$, $e^{1} = e \approx 2.71828$, so our summation result should give the value close to 2.71828 for considerable number of $n$.

exponential series x = 1