我正在做一个 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()
编辑:
上面的代码只有在你有完美的整数交集时才有效。要任意执行这两种操作,您需要在决定使用哪种方法之前检查是否存在完美整数交集。我只是使用了一个简单的 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/