当需要高精度时,Matplotlib无法正确绘制

时间:2017-05-17 12:55:03

标签: python matplotlib

我有一个变化非常小的x-grid:

    xGrid =np.linspace(1-1e-14, 1-1e-16, 30, dtype=np.longdouble)

实际上,python确实记录了这些是不同的值,到目前为止没有舍入错误:

np.diff(xGrid)
Out[3]: 
array([ 3.33066907387547e-16,  3.33066907387547e-16,  3.33066907387547e-16,
        3.33066907387547e-16,  3.33066907387547e-16,  3.33066907387547e-16,
        3.33066907387547e-16,  4.44089209850063e-16,  3.33066907387547e-16,
        3.33066907387547e-16,  3.33066907387547e-16,  3.33066907387547e-16,
        3.33066907387547e-16,  3.33066907387547e-16,  3.33066907387547e-16,
        3.33066907387547e-16,  3.33066907387547e-16,  3.33066907387547e-16,
        3.33066907387547e-16,  3.33066907387547e-16,  3.33066907387547e-16,
        4.44089209850063e-16,  3.33066907387547e-16,  3.33066907387547e-16,
        3.33066907387547e-16,  3.33066907387547e-16,  3.33066907387547e-16,
        3.33066907387547e-16,  3.33066907387547e-16], dtype=float128)

和相应的结果:

results
Out[4]: 
array([-0.008459815023688, -0.008459815023688, -0.008492385739403,
       -0.008492385739403, -0.008492385739403, -0.008524840401542,
       -0.008524840401542, -0.008524840401542, -0.008557185310022,
       -0.008557185310022, -0.008589426764757, -0.008589426764757,
       -0.008621571065665, -0.008621571065665, -0.008653624512661,
       -0.008653624512661, -0.008685593405662, -0.008717484044583,
       -0.008717484044583, -0.00874930272934 , -0.008781055759851,
       -0.008781055759851, -0.008844390057794, -0.008875983925059,
       -0.008907537337741, -0.008939056595756, -0.009002017847451,
       -0.009064918079472, -0.009159264264146, -0.009380267920972])

但如果我

matplotlib无法将其绘制在正确的轴上
    plt.figure()
    plt.plot(xGrid, results)
    plt.savefig('test.pdf')

enter image description here

1 个答案:

答案 0 :(得分:2)

问题不在于值的精确度,而在于x轴定位器的默认设置。如果放大图表,您会看到值全部存在。
要显示所需范围,可以手动设置查看范围:plt.xlim(1-1e-14, 1)。为了获得一些有用的ticklabel,设置具有预定义滴答数的LinearLocator可能很有用。

完整示例:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker

xGrid =np.linspace(1-1e-14, 1-1e-16, 30, dtype=np.longdouble)
y = np.random.rand(len(xGrid))

plt.plot(xGrid, y)
plt.xlim(1-1e-14, 1)

loc = matplotlib.ticker.LinearLocator(numticks=5)
plt.gca().xaxis.set_major_locator(loc)

plt.show()

enter image description here