以图形形式显示除数中带e的分数的结果?

2024-09-30 02:24:20 发布

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

我有一些家庭作业,我需要写一个函数,在图上显示函数:1/1+e^(-x)

因此,我成功地显示了标题中应该写的函数,但是当试图将变量(f_x)定义为计算时,似乎无法将e放在分母中,也无法给它一个指数

为了简化我的问题:我想f_x在给定范围(a和b)的图上显示标题中所写的函数。 如何将函数正确写入“f_x”

f_x=1/(1+(math.frexp)**(-x))不起作用

涅瑟

def plot_sigmoid(a,b):
    if a<b:
        style.use("seaborn")
        plt.title(r'$F(x)=(\frac{1}{1+e^{-x} )})$')
        x=np.arange(a,b+1,0.1)
        f_x=1/(1+math.exp(-x))
        plt.plot()
        plt.show()
    else:
        print("a should be smaller than b (a < b)")
        return

got me:
Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/Tirgul/assign 5 plot-sci-num/Q2.py", line 16, in <module>
    plot_sigmoid(1,3)
  File "C:/Users/User/PycharmProjects/Tirgul/assign 5 plot-sci-num/Q2.py", line 10, in plot_sigmoid
    f_x=1/(1+math.exp(-x))
TypeError: only size-1 arrays can be converted to Python scalars


Tags: 函数标题plotpltmathbeusersnum
1条回答
网友
1楼 · 发布于 2024-09-30 02:24:20

感谢您在问题中包含代码。该错误告诉您math.exp无法执行向量化操作。因为x是一个NumPY数组,所以您正在尝试执行向量化操作。如果您使用for循环,然后一次对一个元素应用math.exp,它将起作用。其他替代方案包括使用map

但是,对于当前的问题,因为您已经导入了NumPy,所以可以按如下所示从NumPy模块使用np.exp。此外,还需要将x和y值传递给plot命令

def plot_sigmoid(a,b):
    if a<b:
        plt.title(r'$F(x)=(\frac{1}{1+e^{-x} )})$')
        x=np.arange(a,b+1,0.1)
        f_x=1/(1+np.exp(-x))
        plt.plot(x, f_x)
        plt.show()
    else:
        print("a should be smaller than b (a < b)")
        return

plot_sigmoid(0, 10)    

enter image description here

相关问题 更多 >

    热门问题