Bird
0
0

Identify the error in this SciPy code that tries to find the root of f(x) = x^2 - 4:

medium📝 Debug Q14 of 15
SciPy - Advanced Optimization
Identify the error in this SciPy code that tries to find the root of f(x) = x^2 - 4:
from scipy.optimize import root

def f(x):
    return x**2 - 4

result = root(f, x0=0)
print(result.root)
AInitial guess x0=0 is not suitable for root finding here.
BFunction f must return a list, not a number.
CThe root function is called incorrectly; it needs extra parameters.
DThere is no error; code runs correctly.
Step-by-Step Solution
Solution:
  1. Step 1: Check function and root call

    Function f returns a number, which is valid for scalar root finding. root() is called with correct syntax.
  2. Step 2: Verify initial guess and output

    Initial guess x0=0 is valid; root() will find root near 0 (which is 2 or -2). Code runs without error.
  3. Final Answer:

    There is no error; code runs correctly. -> Option D
  4. Quick Check:

    Function and root call are correct [OK]
Quick Trick: Check function return type and root call syntax [OK]
Common Mistakes:
  • Thinking initial guess 0 is invalid
  • Expecting function must return list always
  • Assuming root() needs extra parameters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SciPy Quizzes