【问题标题】:How do I plot this function in Python?如何在 Python 中绘制此函数?
【发布时间】:2020-06-26 22:40:05
【问题描述】:

如何使用 numpy 和 matplotlib 绘制此图?

f(t) = t+2,如果t是整数
f(t) = 2**t,否则

假设我的函数是为t > 0 定义的。

这可以绘图吗?

我尝试的方法不起作用...不知道如何解决。

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib
    from math import floor
    
    # csfont = {'fontname':'Comic Sans MS'}
    # hfont = {'fontname':'Helvetica'}
    
    # plt.rcParams["font.family"] = "Comic Sans MS" # "Comic Sans MS"
    
    font = {'family' : 'Comic Sans MS',
            'weight' : 'bold',
            'style'  : 'italic',
            'size'   : 12}
    
    matplotlib.rc('font', **font)
    
    # a,b - the two ends of our interval
    # [-16, 57]
    a = 0.000001
    b = 0.001
    
    def f(t):
        return ( t + 2 if (t==int(t)) else 2**t )
    
    def g(x):
        return np.floor(1/x)
    
    t = np.linspace(a, b, 400)
    f1 = f(t)
    g1 = g(t)
    
    plt.plot(t, f1, 'red', label="f (x)", linewidth=2) # plotting t, f1 separately 
    plt.plot(t, g1, 'green', label="g (x)", linewidth=2) # plotting t, g1 separately
    
    plt.axhline(0, color='k')
    plt.axvline(0, color='k')
    
    # plt.xlabel('X axis', fontsize=14)
    # plt.ylabel('Y axis', fontsize=14)
    
    # plt.title("Illustration of the mean value theorem proof")
    
    # plt.savefig('FFF.png')
    
    plt.legend()
    plt.show()
    
    
    

我也试过t==np.floor(t),但上面写着:The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我知道为什么,但这不是我想要的。我只想在那个 ndarray 上计算这个函数。

【问题讨论】:

标签: python python-3.x numpy matplotlib


【解决方案1】:

您需要vectorize 函数才能对 numpy 数组执行逐元素检查。

import numpy as np

def main():
    a = 0.000001
    b = 0.001
    
    def f(t):
        if int(t) == t:
            return t + 2
        else:
            return 2 ** t

    t = np.linspace(a, b, 400)
    new_f = np.vectorize(f)
    f1 = new_f(t)
    print(f1)

if __name__ == '__main__':
    main()

【讨论】:

    【解决方案2】:

    我们可以从弄清楚如何创建一个整数在哪里的掩码开始,如this post 所述。接下来我们可以查看how np.linspace() works 并意识到您根本没有生成包含任何整数的列表(最大数字为 0.001)。我们可以得到下面的代码

    import numpy as np
    import matplotlib.pyplot as plt
    
    t = np.linspace(0, 10, 201) # 201 numbers from 0 to 10 (the extra one is needed for the endpoint)
    data = np.where(np.mod(t, 1), 2**t, t + 2)  # np.mod will be 0 where there is an int, based on this information we use one of the two formulas
    plt.plot(t, data) # plot results
    plt.show()
    

    理智地检查我们的情节看起来没问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      • 2013-09-15
      • 2019-01-16
      • 1970-01-01
      相关资源
      最近更新 更多