代码之家  ›  专栏  ›  技术社区  ›  meJustAndrew

python中的指数图是一条具有多个拐点的曲线,而不是指数曲线

  •  1
  • meJustAndrew  · 技术社区  · 11 月前

    我试图在python中绘制一个简单的指数。使用下面的代码时,一切正常,并显示指数

    import matplotlib
    matplotlib.use('Agg')
    
    import matplotlib.pyplot as plt
    import numpy as np
    
    def graph(func, x_range):
    x = np.arange(*x_range)
    y = func(x)
    plt.plot(x, y)
    
    graph(lambda x: pow(3,x), (0,20))
    
    plt.savefig("mygraph.png")
    

    但是,如果我将范围从20更改为30,它会绘制一条根本不是指数的曲线。

    enter image description here

    为什么会这样?

    1 回复  |  直到 11 月前
        1
  •  2
  •   Tim Peters    11 月前

    我现在没有时间来解决这个问题,但如果整数运算溢出,这个图看起来很像我所期望的。 numpy 的整数是固定宽度的,与Python的整数(无界)不同。

    特别地,

    >>> 3**20
    3486784401
    >>> _.bit_length()
    32
    

    因此,当事情开始变得疯狂时,结果是溢出了一个32位的整数。尝试替换 3 具有 3.0 在你的 pow(3,x) ?