绘制弧线:图中的异常

Alv*_*pik 2 python numpy matplotlib

import matplotlib.pyplot as plt
import numpy as np

def arc():
    x = np.arange((-np.pi)/4, (np.pi)/4, 0.001)

    f1 = lambda x: 3 * (np.cos(2 * x) )**0.5
    plt.vlines(0, 0, 5)
    plt.plot(x, f1(x), label = '$r=3\sqrt{\cos{2\phi}}$')

    plt.xlabel('$\phi$')
    plt.ylabel('$r(\phi)$')
    plt.legend(loc='best')


    axes = plt.gca()
    axes.set_xlim([-np.pi, np.pi])
    axes.set_ylim([0, 5])
    plt.show()

arc()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我不明白为什么它不会一直到\phi右侧的轴.我该怎么做才能解决这个问题?

Bas*_*els 6

获得所需内容的最佳方法是使用linspace.要获得x与示例中的矢量几乎相同的矢量,您应该这样做

x = np.linspace(-np.pi/4, np.pi/4, round(np.pi / 2 / 0.001) + 1)
Run Code Online (Sandbox Code Playgroud)

或者干脆

x = np.linspace(-np.pi/4, np.pi/4, npoints)
Run Code Online (Sandbox Code Playgroud)

这为您提供了精确的 npoints点数,并保证包含起始值和停止值.

使用np.arange(start, stop, step)为您提供点,start, start+step, start+2*step, ...直到最后一点为止start+n*step < stop.由于浮点不准确,n最后一点是什么并不明显.该手册arange言论:

当使用非整数步骤(例如0.1)时,结果通常不一致.最好在这些情况下使用linspace.

通过使用可变步长生成0到1之间的一些范围,很容易证明这会导致不可预测的行为:

In [21]: for i in range(97,109):
    ...:     r = np.arange(0, 1, 1. / i)
    ...:     print 'step = 1.0 / {}, length = {}, last value = {}'.format(
    ...:         i, len(r), r[-1])
    ...:     
step = 1.0 / 97, length = 97, last value = 0.989690721649
step = 1.0 / 98, length = 99, last value = 1.0
step = 1.0 / 99, length = 99, last value = 0.989898989899
step = 1.0 / 100, length = 100, last value = 0.99
step = 1.0 / 101, length = 101, last value = 0.990099009901
step = 1.0 / 102, length = 102, last value = 0.990196078431
step = 1.0 / 103, length = 104, last value = 1.0
step = 1.0 / 104, length = 104, last value = 0.990384615385
step = 1.0 / 105, length = 105, last value = 0.990476190476
step = 1.0 / 106, length = 106, last value = 0.990566037736
step = 1.0 / 107, length = 108, last value = 1.0
step = 1.0 / 108, length = 108, last value = 0.990740740741
Run Code Online (Sandbox Code Playgroud)

另见相关问题的答案.