如何使用Python和matplotlib绘制任意数学函数?

2024-07-04 17:06:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想画任何数学函数,比如y=x**2或y=sin(x)/x(基本上任何东西)。 问题是,我只能绘制numpy中定义的函数,如np.sinnp.cosnp.tan。 这里的重点是如何避免“硬编码”向量,然后绘制这些向量

如何绘制任意函数?以下是我到目前为止的情况:

import matplotlib.pyplot as plt
import numpy as np

#Let a be starting point on x
#Let b be end point on x
#Let f be the function you wish to plot

CornflowerBlue="6495ed"

def plotf(a,b,f):
    
    x=np.linspace(a,b,num=b*10)
    y=np.array([])
    
    for i in range (len(x)):
       
        y = np.append(y,f(x[i]))
        
    plt.grid(True)
    plt.plot(x,y,color="CornflowerBlue")
    plt.axhline(y=0,color="black")
    return 

Tags: 函数importnumpyplotonasnp绘制
1条回答
网友
1楼 · 发布于 2024-07-04 17:06:39

您可以尝试sympy,因为它应该允许您在不显式硬编码的情况下使用各种数学函数:

from sympy import *

def plotf(a,b,f):
    plot(f, xlim = (a,b)) 

plotf(-10, 10, "sin(x)/x") # or plotf(0, 2, "x**2"), or (almost) whatever

有关详细信息,请参见https://docs.sympy.org/latest/modules/plotting.html

相关问题 更多 >

    热门问题