Bird
0
0

The following code is intended to plot the cumulative integral of cos(x) from 0 to 2π, but it raises an error. What is the error and how to fix it?

medium📝 Debug Q14 of 15
SciPy - Integration with Scientific Ecosystem
The following code is intended to plot the cumulative integral of cos(x) from 0 to 2π, but it raises an error. What is the error and how to fix it?
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import cumtrapz

x = np.linspace(0, 2*np.pi, 100)
y = np.cos(x)

integral = cumtrapz(y, x)
plt.plot(x, integral)
plt.show()
AError: plt.plot cannot plot arrays; fix by converting to list
BError: cumtrapz returns array shorter by 1; fix by plotting plt.plot(x[1:], integral)
CError: cumtrapz needs y first then x; fix by swapping arguments
DError: np.cos requires integer input; fix by converting x to int
Step-by-Step Solution
Solution:
  1. Step 1: Identify cumtrapz output length

    cumtrapz returns an array with length one less than input arrays.
  2. Step 2: Fix plotting mismatch

    Plot x[1:] with integral to match array sizes and avoid error.
  3. Final Answer:

    Error: cumtrapz returns array shorter by 1; fix by plotting plt.plot(x[1:], integral) -> Option B
  4. Quick Check:

    cumtrapz output length = input length - 1 [OK]
Quick Trick: cumtrapz output shorter by 1, plot with x[1:] [OK]
Common Mistakes:
  • Plotting full x with shorter integral array
  • Trying to convert floats to int unnecessarily
  • Swapping arguments of cumtrapz incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SciPy Quizzes