Question:
Hello everyone, im new to programming and i need a little help.?
2012-11-17 22:46:41 UTC
Hello everyone, im new to programming and i need a little help.
Write a C program the computes the value e^x by using the formula :
e^x = 1 + 1/1!*x + 1/2!*x^2 +...+ 1/n!*x^n
The sum stops when 1/n!*x^n<=epsilon , 0First x and epsilon are inputed from the keyboard .
Please HELP ME as im not too sure how to started.
Three answers:
modulo_function
2012-11-17 23:07:16 UTC
There's an even smarter way



each term that you're adding is related to the previous term by



term = term*x/n

sum = sum + term;

where n is your loop counter.
2012-11-17 23:00:44 UTC
when you use ! do u mean factorial ..

u need to use a diffrent header in that case

try splitting the equation up with more variables to simplify it
Jared
2012-11-17 22:58:54 UTC
There are two ways you can do this (smart way and dumb way):



Dumb Way:



Write your own factorial and exponential functions (assume non-negative integer exponents)...it's really not that hard:



x^n <-- multiply x by itself, n times...note that x⁰ = 1 <-- this should be the initial value



That's a simple for loop:



double exp(double x, int n){

int i;

double ans = 1.0;



for(i = 0; i < n; ++i){

ans *= x;

}



return ans;

}



(note that there is a more efficient, recursive way to do this--but it will be unnecessary too if you do it the "smart" way later on)



Likewise, the factorial is just a loop: n! = n * (n - 1) * (n - 2)...or you could reverse that: 1 * 2 * 3 * ... * (n - 1) * n



This one is even easier, just start with 1 and go to n, multiplying the results:



int factorial(int n){

int i;

int ans = 1;

for(i = 1; i <= n; ++i){

ans *= i;

}



return ans;

}



So, then just use those two functions to compute each term in the series. Keep a total and stop once the term becomes <= episilon





The smart way is to realize that you can write the terms as a recursive sequence:



a₀ = 1

a₁ = x/1

a₂ = x² / 2 = x * a₁

a₃ = x³ / 6 = x * a₂ / 3

a₄ = x⁴ / 24 = x * a₃ / 4

...



Do you see the pattern?



a₀ = 1

a_n = x / n * a_{n - 1}





So NOW, you can just add up the total using that relation:

double my_exp(double x, double eps){



double term = 1;

double sum = term;

int n = 1;



while(...) { // you figure out what should go here

term *= x / n++;

sum += term;

}



return sum;

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...