Question
Consider the following function:
double f(double x){
if( abs(x*x - 3) < 0.01) return x;
else return f(x/2 + 1.5/x);
}
Give a value (to 2 decimals) such that will return : _____.
Official answer and solution
- Accepted answers
- 1.72 to 1.74
- From
- Official GATE 2014 answer key
Solution
Identify the base termination condition under which the recursive function returns immediately without recursive calls.
-
Code Analysis:
double f(double x){ if( abs(x*x - 3) < 0.01) return x; else return f(x/2 + 1.5/x); } -
Condition for :
- For to return immediately (or as a fixed point), the initial value must satisfy the base condition:
- This inequality translates to:
- For to return immediately (or as a fixed point), the initial value must satisfy the base condition:
-
Evaluating :
- Taking positive roots:
- Since , setting satisfies:
- Thus, immediately returns .
- Any value in the range (or ) is accepted by the official answer key.
- Taking positive roots:
Final answer
1.73
Common trap
Trying to solve for convergence of all iterations rather than observing that the base case returns q directly when |q^2 - 3| < 0.01.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2014 Computer Science and Information Technology (CS) Session 2
- Question
- 50 of 65, printed as CS Q.40
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.