### Thread: exponential function in c

1. No Profile Picture
Junior Member
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2003
Posts
16
Rep Power
0

#### exponential function in c

hello,
if have a problem with an exercise:
the exponetial function is defined by

e=1+x/1!+x²/2!+x³/3!+...x^n/n!+...

now i should write a function, when x ist given it returns the value of e^x

i wrote a function that should work for the factorial.but i have no idea how to continue. thats my code so far

Code:

#include <stdio.h>

main()
{
int factorial (int n);

float e;

printf ("enter a integer to calculate the e function :");
scanf ("%d",&x);

e=
}
int factorial (int n)
{
int nfac;

if (n<0) return 0;

for ( nfac = 1; n > 0; n--)
nfac *= n;
return nfac;
}

i hope somebody can help me.
thanks
2. I have no idea what your code is trying to do (I am a biochemist), but at least this will compile and run:

Code:
```#include <stdio.h>

int factorial (int n);

int main() {
int x;
float e;

printf ("enter a integer to calculate the e function :");
scanf ("%d",&x);

e=factorial(x);
printf("e: %f\n", e);

return 0;
}

int factorial (int n) {
int nfac;

if (n<0) return 0;

for ( nfac = 1; n > 0; n--)
nfac *= n;
return nfac;
}```
3. Each term in the equation can be expressed as x^i/i!

Try expressing the i-th term in terms of the (i-1)th term and then using the following logic.

double i_term = some_initial_value;
double result = 1.0;

for (int i = 1; i < some_length; ++i)
{
i_term = some_function(i_term, x, i);
result += i_term;
}

The basic philosophy is that, each time through the loop, i_term is updated so it will be x^i/i!, and you just add that to result.

I'll leave the specification of some_initial_value, some_function(), and some_length as an exercise. Working out what they should or could be is actually the point of this homework exercise.

Incidentally, note that in the above i! is never computed. One reason is that i! becomes too big to be stored in an int even for relatively small i.

The formula you've given is actually called a series expansion. It is not actually the definition of e^x. If you have an infinite number of terms, the value of the series expansion will be e^x. The problem is that takes infinite time to compute, so you need to truncate the series.....