The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+11 votes
2.2k views

Consider the following $C$ function.

For large values of $y$, the return value of the function $f$ best approximates

float f,(float x, int y) {
    float p, s; int i;
    for (s=1,p=1,i=1; i<y; i++) {
        p *= x/i;
        s += p;
    }
    return s;
}

  1. $x^y$
  2. $e^x$
  3. $\text{ln} (1+x)$
  4. $x^x$
asked in Algorithms by Veteran (59.7k points)
edited by | 2.2k views
+1
No need to remember series expansion just use Taylor series for getting expansion of f(x).

3 Answers

+21 votes
Best answer

A simplified version of the given program can be written as:

float f(float x, int y) {
    float p=1, s=1; 
    int i;
    for (i=1; i<y; i++) {
        p = p * (x/i);
        s = s + p;
    }
    return s;
}

We can take $p=1,s=1$ initialization outside of for loop because there is no condition checking in for loop involving $p,s$ .

$i$ $p= p $*$ (x/i)$ $s= s + p$
$1$ $x$ $1+x$
$2$ $\frac{x^{2}}{2}$ $1+x+\frac{x^{2}}{2}$
$3$ $\frac{x^{3}}{6}$ $1+x+\frac{x^{2}}{2}+\frac{x^{3}}{6}$
$4$ $\frac{x^{4}}{24}$ $1+x+\frac{x^{2}}{2}+\frac{x^{3}}{6}+\frac{x^{4}}{24}$
$n$ $\frac{x^{n}}{n!}$ $e^x$
 $e^x = \displaystyle{\sum_{n=0}^{\infty} \frac{x^n}{n!}}  = 1+x+\frac{x^{2}}{2}+\frac{x^{3}}{6} +\frac{x^{4}}{24}+ \ldots+\frac{x^{n}}{n!}$

Hence, option B is answer.

answered by Boss (23.1k points)
edited by
+23 votes

$$\begin{array}{l}
i = 1 &\rm then& p = x &\&& s = 1 + x\\[1em]
i = 2 &\rm then& p = \frac{x^2}{2} &\&& s = 1+x+\frac{x^2}{2}
\end{array}$$

As $y$ tends to infinity, $s$ tends to  $e^x$.

Hence, the correct answer is option B.

answered by Boss (31.9k points)
edited by
0
@Pooja Thanks for compact answers.I have been following your answers. :) just a minute correction needed in the above answer when i=1 p=x.
0

@Pooja Palod good answer but just small improvement, Please put factorial symbol in denominator.

0
if i do with example then e^2 is 7.38 but it gives 5 ... why is this difference ?
+1
@sid1221 :- e^x is an infinite series,so for large value y,if you run,the output will approximate to you answer
0 votes

I am using substitution method to get answer

answered by Active (3.5k points)
Answer:

Related questions



Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

44,199 questions
49,669 answers
163,549 comments
65,818 users