The value of Exponential Function e^x can be expressed using following Taylor Series.

e^x = 1 + x/1! + x^2/2! + x^3/3! + ……

How to efficiently calculate the sum of above series?
The series can be re-written as

e^x = 1 + (x/1) (1 + (x/2) (1 + (x/3) (……..) ) )
Let the sum needs to be calculated for n terms, we can calculate sum using following loop.

for (i = n – 1, sum = 1; i > 0; –i )
sum = 1 + x * sum / i;
Following is implementation of the above idea.

[pastacode lang=”c” manual=”%2F%2F%20Efficient%20program%20to%20calculate%20e%20raise%20to%20the%20power%20x%0A%23include%20%3Cstdio.h%3E%0A%20%0A%2F%2FReturns%20approximate%20value%20of%20e%5Ex%20using%20sum%20of%20first%20n%20terms%20of%20Taylor%20Series%0Afloat%20exponential(int%20n%2C%20float%20x)%0A%7B%0A%20%20%20%20float%20sum%20%3D%201.0f%3B%20%2F%2F%20initialize%20sum%20of%20series%0A%20%0A%20%20%20%20for%20(int%20i%20%3D%20n%20-%201%3B%20i%20%3E%200%3B%20–i%20)%0A%20%20%20%20%20%20%20%20sum%20%3D%201%20%2B%20x%20*%20sum%20%2F%20i%3B%0A%20%0A%20%20%20%20return%20sum%3B%0A%7D%0A%20%0A%2F%2F%20Driver%20program%20to%20test%20above%20function%0Aint%20main()%0A%7B%0A%20%20%20%20int%20n%20%3D%2010%3B%0A%20%20%20%20float%20x%20%3D%201.0f%3B%0A%20%20%20%20printf(%22e%5Ex%20%3D%20%25f%22%2C%20exponential(n%2C%20x))%3B%0A%20%20%20%20return%200%3B%0A%7D” message=”C Program” highlight=”” provider=”manual”/]

Output:

e^x = 2.718282
[ad type=”banner”]