edited by
10,022 views
27 votes
27 votes

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$
edited by

3 Answers

Best answer
52 votes
52 votes

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$ .
$$\begin{array}{|l|l|l|} \hline \text{$i$} & \text{$p= p $*$ (x/i)$} & \text{$s=s+p$}\\\hline \text{1} & \text{$x$} & \text{$1+x$} \\\hline \text{2} & \text{$\frac{x^{2}}{2}$} & \text{$1+x+\frac{x^{2}}{2}$}\\\hline \text{3} & \text{$\frac{x^{3}}{6}$} & \text{$1+x+\frac{x^{2}}{2}+\frac{x^{3}}{6}$} \\\hline  \text{4} & \text{$\frac{x^{4}}{24}$} & \text{$1+x+\frac{x^{2}}{2}+\frac{x^{3}}{6}+\frac{x^{4}}{24}$}\\\hline \text{n} & \text{$\frac{x^{n}}{n!}$} & \text{$e^x$} \\\hline \end{array}$$

$$\begin{array}{|l|} \hline  \text{$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!}$} \\\hline \end{array}$$

Hence, option B is answer.

edited by
31 votes
31 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.

edited by
Answer:

Related questions

50 votes
50 votes
11 answers
4
Kathleen asked Sep 17, 2014
14,103 views
The following are the starting and ending times of activities $A, B, C, D, E, F, G$ and $H$ respectively in chronological order: $“a_s \: b_s \: c_s \: a_e \: d_s \: c_...