使用linspace生成数组后调用sin、tan绘图时遇TypeError求助
Hey there, let's break down why you're seeing this error and how to fix it quickly!
The Root Cause
That TypeError: only size-1 arrays can be converted to Python scalars happens because you're likely using Python's built-in math.tan() function instead of NumPy's np.tan().
Here's the key difference:
math.tan()only works with single scalar values (liketan(0.5)), not entire arrays.- Your
xvariable is a NumPy array created withlinspace(), so passing it tomath.tan()throws an error because the function can't handle array inputs.
(Side note: Your sin(x) call worked probably because you were using NumPy's np.sin()—either via from numpy import sin or import numpy as np and np.sin()—which does support array operations.)
The Solution
Just make sure you're using NumPy's version of tan for your array. Here's the corrected code:
import numpy as np import matplotlib.pyplot as plt # Don't forget to import matplotlib for plotting! # Generate your x array x = np.linspace(0, 2 * np.pi, 50) # Plot sin(x) (using NumPy's sin) plt.plot(x, np.sin(x)) # Plot tan(x) with NumPy's tan (this fixes the error) plt.plot(x, np.tan(x)) # Optional: Limit y-axis to avoid extreme values near π/2 and 3π/2 plt.ylim(-10, 10) plt.show()
If you had previously imported tan from the math module (like from math import tan), just remove that line or explicitly use np.tan() to override it.
Quick Bonus Tip
When plotting tan(x), you'll notice the line breaks near π/2 and 3π/2—this is normal because the tangent function approaches positive/negative infinity at those points. Setting a y-axis limit (like plt.ylim(-10,10)) makes the plot look cleaner without hiding the core behavior of the function.
内容的提问来源于stack exchange,提问作者Ashley Thomas

