我做了一些作业,需要编写一个在图形上显示该函数的函数:1/1 + e ^(-x)。

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

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

f_x=1/(1+(math.frexp)**(-x))无效

f_x=1/(1+math.exp(-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

最佳答案

感谢您在问题中包含代码。该错误告诉您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)


python - 用除数中的e作为图表显示分数的结果?-LMLPHP

关于python - 用除数中的e作为图表显示分数的结果?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56602887/

10-12 22:24