python - 情节显示 Jupyter 中的错误点

标签 python python-3.x jupyter-notebook jupyter

我正在做一个 Python 测试来绘制一些函数。

问题是两个函数在同一个 X 处相交的点不正确。


import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

x = np.arange(-10,10,1)

def f(x): 
    return x+30

def z(x):
    return x*x

plt.figure(figsize=(5,5))
plt.plot(x, f(x).astype(np.int))
plt.plot(x, z(x).astype(np.int))
plt.title("Gráfico de función" )
plt.xlabel("X")
plt.ylabel("Y")

idx = np.argwhere(np.diff(np.sign(f(x) - z(x)))).flatten()
plt.plot(x[idx], f(x[idx]), 'ro')

plt.legend(["F","Z"])

plt.show()

我预计只有两点,但在剧情中出现了四点。其中两个是不正确的。

最佳答案

此错误与绘图本身无关,而是与您在交集为整数值时获取这种情况下的点的方法有关。当采用 np.sign 的 np.diff 时,在交点处从 -1 到 0 再到 1,在 4 个位置处得到 1。如果交集不是整数,您将得到 -1 到 1 并得到正确答案。如果您尝试这样做,您可以找到整数交点:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

x = np.arange(-10,10,1)

def f(x): 
    return x+30.

def z(x):
    return x*x

plt.figure(figsize=(5,5))
plt.plot(x, f(x).astype(np.int))
plt.plot(x, z(x).astype(np.int))
plt.xlabel("X")
plt.ylabel("Y")

#Say only get args where there is no sign (i.e. zero).
idx = np.argwhere((np.sign(f(x) - z(x))==0)) 

plt.plot(x[idx], f(x[idx]), 'ro')

plt.legend(["F","Z"])
plt.show()

enter image description here

编辑: 上面的代码只有在你有完美的整数交集时才有效。要任意执行这两种操作,您需要在决定使用哪种方法之前检查是否存在完美整数交集。我只是使用了一个简单的 for 循环来执行此操作,但我相信还有更优雅的方法来执行此操作。

for v in np.sign(f(x) - z(x)):
    if v==0:
        idx = np.argwhere(np.sign(f(x) - z(x))==0)
        break
    else:
        idx = np.argwhere(np.diff(np.sign(f(x) - z(x))))

关于python - 情节显示 Jupyter 中的错误点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55564396/

相关文章:

python - Pygame 窗口无法从 python 脚本内部打开

python - 如何获取字符串中的名字?

python - numpy.ndarray 的类型提示/注释 (PEP 484)

python-3.x - 在客户端应用程序上将一个套接字与多个窗口一起使用

amazon-web-services - 如何在 SageMaker 上安排任务

python - Google Colab 在处理包含大量文件的云端硬盘文件夹时遇到问题

python - 如何将具有不规则列的html代码转换为嵌套的json文件?

python-3.x - TensorFlow中的对抗图像

python - Jupyter notebook 选择旧版本的 numpy

python - 使用正则表达式将数据从字符串移动到 pandas 数据框?