有没有一种方法可以通过input()绘制多项式方程式?

时间:2019-12-06 23:17:46

标签: python matplotlib graph

几个月前(11年级),我开始学习Python,并决定通过在Python中创建一个微型图形计算器来测试我的知识。使用matplotlib.pyplot我可以绘制sin(),cos()和tan()。现在,我希望用户根据y输入一个多项式方程,然后显示该方程的图,但是我遇到了类型错误。

import matplotlib.pyplot as plt 
import numpy as np

x = np.arange(-10, 10, 0.1) 
y = input("Enter polynomial equation in terms of y\ny = ") 
plt.plot(x, y) 
plt.show()

3 个答案:

答案 0 :(得分:0)

a = input("x^2 coefficient: ")
b = input("x^1 coefficient: ")
c = input("x^0 coefficient: ")

y = (a * (x * x)) + (b * x) + c

plt.plot(x, y)

答案 1 :(得分:0)

Sympy,Python的符号数学库,可用于根据用户输入的函数创建图:

import matplotlib.pyplot as plt
import sympy as sy
from sympy.abc import x

y = input("Enter equation in terms of x\ny = ")
sy.plot(sy.sympify(y), (x, -10, 10) )
plt.show()

输入“ sin(x)/ x”时: sin(x)/x

答案 2 :(得分:0)

输入不会自动评估。有充分的理由。如果要评估输入,则需要使用eval

明确地进行输入
y = eval(input(...))

因此

import matplotlib.pyplot as plt 
import numpy as np

x = np.arange(-10, 10, 0.1) 
y = eval(input("Enter polynomial equation in terms of y\ny = "))

plt.plot(x, y) 
plt.show()