我有一些家庭作业,我需要写一个函数,在图上显示函数: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
感谢您在问题中包含代码。该错误告诉您
math.exp
无法执行向量化操作。因为x
是一个NumPY数组,所以您正在尝试执行向量化操作。如果您使用for循环,然后一次对一个元素应用math.exp
,它将起作用。其他替代方案包括使用map
但是,对于当前的问题,因为您已经导入了NumPy,所以可以按如下所示从NumPy模块使用
np.exp
。此外,还需要将x和y值传递给plot命令相关问题 更多 >
编程相关推荐