数值错误:x 和 y 必须具有相同的第一维度,但形状分别为(100,)和((1,))。

5

我想使用Python、numpy和matplotlib绘制一个简单的函数,但是当我执行脚本时,它返回了标题中描述的ValueError错误。

这是我的代码:

"""Geometrical interpretation: In Python, plot the function y = f(x) = x**3 − (1/x)
and plot its tangent line at x = 1 and at x = 2."""

import numpy as np
import matplotlib.pyplot as plt


def plot(func):
    plt.figure(figsize=(12, 8))
    x = np.linspace(-100, 100, 100)
    plt.plot(x, func, '-', color='pink')
    plt.show()
    plt.close()


plot(lambda x: x ** 3 - (1 / x))

请帮助这位初学者 :)


在问题中显示真实的错误信息(格式化和未编辑)。 - ctrl-alt-delor
那是复制粘贴的错误。 - Miguel Valente
OK。在问题中显示格式化的错误消息。 - ctrl-alt-delor
1个回答

5

实际上,这是一个不错的尝试。您只需要使用y = func(x)添加变量y。然后plt.plot(x,y)...

因此,这样可以工作:

import numpy as np
import matplotlib.pyplot as plt


def plot(func):
    plt.figure(figsize=(12, 8))
    x = np.linspace(-100, 100, 100)
    y = func(x)
    plt.plot(x, y, '-', color='pink')
    plt.show()
    plt.close()


plot(lambda x: x ** 3 - (1 / x))

结果:

在此输入图片描述


1
谢谢,它确实起作用了。我只是在等待标记为已解决。你能解释一下为什么这样解决了这个问题吗? - Miguel Valente
是的,你正确地将lambda函数传递为“func”,但你没有使用它。这个图需要一系列的x和y值...所以如果你执行print(y),你会看到y的值... - D.L
哦,我明白了。再次感谢您的帮助 :) - Miguel Valente
因此,实际上,您需要使用您创建的func()计算每个x值的y值。 - D.L

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接