绘制方程显示一个圆

Plot equation showing a circle

以下公式用于对二维space中的点进行分类:

f(x1,x2) = np.sign(x1^2+x2^2-.6)

所有点都在 space X = [-1,1] x [-1,1] 中,每个 x 的选取概率相同。

现在我想可视化等于的圆:

0 = x1^2+x2^2-.6

x1 的值应在 x 轴上,x2 的值应在 y 轴上。

这一定是可能的,但我很难将方程式转化为绘图。

绘制 x 值并计算相应的 y 值如何?

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1, 1, 100, endpoint=True)
y = np.sqrt(-x**2. + 0.6)

plt.plot(x, y)
plt.plot(x, -y)

生产

这显然可以做得更好,但这只是为了演示...

您可以使用等高线图,如下(基于http://matplotlib.org/examples/pylab_examples/contour_demo.html处的示例):

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1.0, 1.0, 100)
y = np.linspace(-1.0, 1.0, 100)
X, Y = np.meshgrid(x,y)
F = X**2 + Y**2 - 0.6
plt.contour(X,Y,F,[0])
plt.show()

这会产生下图

最后,一些一般性陈述:

  1. x^2 并不代表您 认为 它在 python 中的意思,您必须使用 x**2.
  2. x1x2 非常误导(对我来说),特别是如果你声明 x2 必须在 y 轴上。
  3. (感谢 Dux)您可以添加 plt.gca().set_aspect('equal') 通过使轴相等,使图形看起来实际上是圆形的。

@BasJansen 的解决方案肯定会让你到达那里,它要么非常低效(如果你使用很多网格点)要么不准确(如果你只使用很少的网格点)。

直接画圆就可以了。给定 0 = x1**2 + x**2 - 0.6 则得出 x2 = sqrt(0.6 - x1**2)(如 Dux 所述)。

但您真正想要做的是将笛卡尔坐标转换为极坐标。

x1 = r*cos(theta)
x2 = r*sin(theta)

如果您在圆方程中使用这些替换,您会看到 r=sqrt(0.6)

所以现在您可以将其用于您的情节:

import numpy as np
import matplotlib.pyplot as plt

# theta goes from 0 to 2pi
theta = np.linspace(0, 2*np.pi, 100)

# the radius of the circle
r = np.sqrt(0.6)

# compute x1 and x2
x1 = r*np.cos(theta)
x2 = r*np.sin(theta)

# create the figure
fig, ax = plt.subplots(1)
ax.plot(x1, x2)
ax.set_aspect(1)
plt.show()

结果:

# x**2  + y**2 = r**2
r = 6
x = np.linspace(-r,r,1000)
y = np.sqrt(-x**2+r**2)
plt.plot(x, y,'b')
plt.plot(x,-y,'b')
plt.gca().set_aspect('equal')
plt.show()

产生:

用复数画圆

思路:将一个点乘以复指数 () 使该点在圆上旋转

将 numpy 导入为 np 将 matplotlib.pyplot 导入为 plt

将 numpy 导入为 np 将 matplotlib.pyplot 导入为 plt

num_pts=20 # number of points on the circle
ps = np.arange(num_pts+1)
# j = np.sqrt(-1)
pts = np.exp(2j*np.pi/num_pts *(ps))

fig, ax = plt.subplots(1)
ax.plot(pts.real, pts.imag , '-o')
ax.set_aspect(1)
plt.show()