所以我在绘制if语句函数时遇到了一个问题。有人能告诉我哪里出了问题吗?守则如下:
import numpy as np
import matplotlib.pyplot as plt
#x-axis
x_1 = np.arange(-20,20,0.001)
#defining the function
def h(x):
"""
input: x \in R
oupit: h(x) defined above in R.
"""
if x == 0:
return 1
else:
return np.sin(x)/x
def g(x):
"""
input: x \in R
oupit: g(x) defined above in R.
"""
return np.cos(x)
#drawing the function
plt.plot(x_1,h(x_1),label = r"$\frac{\sin(x)}{x}$",color="red")
plt.legend()
plt.plot(x_1,g(x_1),label = r"$\cos(x)$",color="blue")
plt.legend()
plt.grid(linestyle="dotted")
plt.ylabel("$f(x)$")
#plt.savefig('img231.pdf')
plt.show()
主要问题可能与plt.plot(x_1,h(x_1))
一致。感谢您的回答:)~谢谢,Y
要在numpy中编写
if
测试,需要np.where
:np.where(x == 0, 1, np.sin(x)/x)
。 这仍然会写入一条警告,警告被零除,可以使用with np.errstate(divide='ignore')
抑制该警告还要注意
np.arange(-20, 20, 0.001)
生成40000
值,这与屏幕上的像素数相比是相当高的(与打印机上的点相比是偶数)。使用np.linspace()
可以更轻松地控制使用的点数。使用过多的点可能会不必要地减慢计算和打印速度调用
plt.legend()
两次可能会有点混乱。第二次调用将删除第一个图例相关问题 更多 >
编程相关推荐