在 matplotlib 中用输入绘制抛物线

所以我在python中创建了一个二次方程求解器,我想要一个图表来配合它。我希望这张图描绘抛物线。


a = 二次方程中 a 的输入


b = 二次方程中 b 的输入


c = 二次方程中 c 的输入


y = -b/2*a (向量)


import math

a = int(input('Input a: '))

b = int(input('Input b: '))

c = int(input('Input c: '))

discrim = int((b*b) - 4*a*c) 

posi = (-b + (math.sqrt(discrim)))/(2*a)

neg = (-b - (math.sqrt(discrim)))/(2*a)



if b > 0 and c > 0 and posi < 0:

  posi = -posi

  if neg < 0:

    neg = -neg


y = -b/2*a

vector = (neg+posi)/2, y)

使用这段代码,我有我的 x 截距和足以创建抛物线的向量,我只是不确定如何使用 MatPlotLib 将这些值转换为图形。请提出任何问题。



幕布斯7119047
浏览 160回答 1
1回答

慕工程0101907

我在你的代码中做了一些更正。下面的代码将绘制任何抛物线。您可以在绘图中添加零点和极值点。import matplotlib.pyplot as pltimport mathimport numpy as npa = int(input('Input a: '))b = int(input('Input b: '))c = int(input('Input c: '))# calculate delta and zero pointsdelta = b**2 - 4*a*cif delta > 0:&nbsp; &nbsp; x_1 = (-b + math.sqrt(delta))/(2*a)&nbsp; &nbsp; x_2 = (-b - math.sqrt(delta))/(2*a)if delta == 0:&nbsp; &nbsp; x_0 = -b/(2*a)else:&nbsp; &nbsp; pass# calculate parabola extreme coordinatesp = -b/(2*a)q = -delta/(4*a)extreme = [p,q]# define parabola functiondef parabola(x,a,b,c):&nbsp; &nbsp; y = a*x**2 + b*x + c&nbsp; &nbsp; return y# plot functionx = np.linspace(int(p)-5,int(p)+5,100)y = parabola(x,a,b,c)plt.plot(x,y)plt.axhline(y=0, color='black', linestyle='-')plt.axvline(x=0, color='black', linestyle='-')plt.text(p-0.5, q-3, '[' + str(round(p,2)) +',' + str(round(q,2)) + ']',color='orange', fontsize=9)plt.plot(p, q, marker="o")if delta > 0:&nbsp; &nbsp; plt.plot(x_1, 0, marker="o", color='green')&nbsp; &nbsp; plt.text(x_1 - 0.5, 2, '[' + str(round(x_1,2)) + ']', color='green', fontsize=9)&nbsp; &nbsp; plt.plot(x_2, 0, marker="o", color='green')&nbsp; &nbsp; plt.text(x_2 - 0.5, 2, '[' + str(round(x_2,2)) + ']', color='green', fontsize=9)if delta == 0:&nbsp; &nbsp; plt.plot(x_0, 0, marker="o", color='green')&nbsp; &nbsp; plt.text(x_0 - 0.5, 2, '[' + str(round(x_0,2)) + ']', color='green', fontsize=9)plt.show()样本结果:https://i.stack.imgur.com/bNprP.png
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python