用除数中的e来显示分数的结果吗?

时间:2019-06-14 17:37:55

标签: python matplotlib graph

我做了一些家庭作业,需要编写一个在图形上显示该函数的函数: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

1 个答案:

答案 0 :(得分:1)

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