无法绘制函数

2024-09-29 17:21:45 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在绘制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


Tags: theinimportinputreturnifplotdef
1条回答
网友
1楼 · 发布于 2024-09-29 17:21:45

要在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()两次可能会有点混乱。第二次调用将删除第一个图例

import numpy as np
import matplotlib.pyplot as plt

x_1 = np.linspace(-20, 20, 1000)

def h(x):
    with np.errstate(divide='ignore'):
        return np.where(x == 0, 1, np.sin(x) / x)

def g(x):
    return np.cos(x)

plt.plot(x_1, h(x_1), label=r"$\frac{\sin(x)}{x}$", color="crimson")
plt.plot(x_1, g(x_1), label=r"$\cos(x)$", color="cornflowerblue")
plt.grid(linestyle="dotted")
plt.ylabel("$f(x)$")
plt.legend()
plt.show()

resulting plot

相关问题 更多 >

    热门问题