下面是我正在try 绘制的函数

def f(x):
    return 50 * (1 / (1 + ((50/5)-1) * e ** -max(0, 0.1 * x)))

try 使用matplotlib绘制时出现以下错误: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我相信这是因为我的功能中的-max(0, 0.1 * x)部分.

以下是我的matplotlib代码的完整版本:

import matplotlib.pyplot as plt
import numpy as np
from math import e

# 100 linearly spaced numbers between -10 and 100
x = np.linspace(-10,100,200)

def f(x):
    return 50 * (1 / (1 + ((50/5)-1) * e ** -max(0, 0.1 * x)))

# setting the axes at the centre
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

# plot the function
plt.plot(x,f(x), 'r')

# show the plot
plt.show()

研究this错误使我发现,虽然max()函数通常计算数字,但由于它传递的x是np.linspace()而不是数字,因此它无法计算它.

如何在不进行内部更改的情况下绘制f(x)函数(因为这会 destruct 我已有的一些单元测试)

推荐答案

我重读了您的问题,您想知道函数是否可以按原样运行而无需修改,答案是肯定的.你需要根据当前的设计逐一进行判断.

为此,我创建了一个包含要计算的数字长度的zeros数组,并将函数值插入到每个索引中.结果与前面的答案类似.

import matplotlib.pyplot as plt
import numpy as np
from math import e

# 100 linearly spaced numbers between -10 and 100
N=200
x = np.linspace(-10,100,N)

def f(x):
    return 50 * (1 / (1 + ((50/5)-1) * e ** -max(0, 0.1 * x)))

f_eval = np.zeros(N)
for idx, i in enumerate(x):
    f_eval[idx] = f(i)


# setting the axes at the centre
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

# plot the function
plt.plot(x,f_eval, 'r')

# show the plot
plt.show()

result

Python相关问答推荐

tempfile.mkstemp(text=.)参数实际上是什么?

使用unmanagedexports从Python调用的c#DLC

为什么使用SciPy中的Distance. cos函数比直接执行其Python代码更快?

键盘.任务组

Ibis中是否有一个ANY或ANY_UTE表达,可以让我比较子查询返回的一组值中的值?

如何将Matplotlib的fig.add_axes本地坐标与我的坐标关联起来?

使用polars .滤镜进行切片速度比pandas .loc慢

Locust请求中的Python和参数

Deliveryter Notebook -无法在for循环中更新matplotlib情节(保留之前的情节),也无法使用动画子功能对情节进行动画

Matlab中是否有Python的f-字符串等效物

. str.替换pandas.series的方法未按预期工作

输出中带有南的亚麻神经网络

将输入管道传输到正在运行的Python脚本中

所有列的滚动标准差,忽略NaN

索引到 torch 张量,沿轴具有可变长度索引

Python列表不会在条件while循环中正确随机化'

如何启动下载并在不击中磁盘的情况下呈现响应?

我的字符串搜索算法的平均时间复杂度和最坏时间复杂度是多少?

在Python中调用变量(特别是Tkinter)

基于行条件计算(pandas)