在 matplotlib 中绘制一个字符串函数 // 将 str 解释为 python 代码?

问题描述 投票:0回答:1

我正在创建一个 RPN 计算器,它试图绘制用户给定的函数。例如,如果用户输入“x sin 3 *plot”,我希望它绘制sin(x)*3。其代码如下。注意:问题出在“if提示==”plot“:”下

    userInputX=""               #userInputX is always replaced before
                                #running again, so it can be set once here
    while True:        
        print("----------------------------------------------------------")
        if not myqueue.isEmpty(): # Display both postfix and infix
            print("Postfix: "+str(myqueue))
            print("Infix: "+StackCalc.postfix2infix(myqueue))
        prompt=input(">")
        if prompt == "exp" or prompt == "^": prompt = "**"  #<- Easiest way to stop errors with eval(),
        if prompt=="quit": break                            #+ consistent formatting while still accepting exp/^

        if prompt=="run":
            if myqueue.find("x") is True:                   # If run, get x value from user, set post2in to the 
                userInputX=input("Enter x value: ")         #result of postfix2infix except replace the x with userinput
            post2in=StackCalc.postfix2infix(myqueue).replace("x",userInputX)
            print("Solution using infix:",eval(post2in))    #then evaluate it
            print("Solution using postfix:",StackCalc.evaluate_postfix(myqueue,userInputX))
            continue #skip to next iteration, as "run" shouldnt be pushed to queue

        if prompt=="plot":
            post2in=StackCalc.postfix2infix(myqueue)
            usrInp=input("Enter values of xmin, xmax, nbp: ")#input format "0.5 10.5 1"
            usrInp=usrInp.split()                       # Make it a list,
            xmin,xmax,nbp=usrInp[0],usrInp[1],usrInp[2] #set values to input
            
            #this is where it gets questionable
            x=np.linspace(float(xmin),float(xmax),int(nbp))
            plt.plot(x,post2in)   # this is specifically where the issue lies
            plt.title("f(x)="+str(post2in))
            plt.show()
            continue # dont push "plot" to queue


        if prompt!="flush":
            if prompt == "exp" or prompt == "^": prompt = "**"
            myqueue.enqueue(prompt)     # same code as optn. 2
        else:
            myqueue.flush()

需要明确的是,postfix2infix 将用户的函数作为字符串返回。对于我上面使用的示例,它将返回“sin(x)*3”作为字符串,我需要将其解释为函数/python 代码。这可能吗?例如,如果我硬编码 plt.plot(x,sin(x)*3) ,它会按预期工作,但它不会绘制任何其他函数。 另外,它可能看起来评论过多,但这是针对一个类的,所以它是为了证明我知道代码在做什么(不仅仅是 ai gen'd)

python-3.x matplotlib
1个回答
-2
投票

Lenzuola Animalier 伦佐拉(Lenzuola)无可挑剔地与动物们打交道,并在所有优雅的节中表现得淋漓尽致。 Scegli il design perfetto e vivi il lusso ogni notte.

© www.soinside.com 2019 - 2024. All rights reserved.