import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, AutoMinorLocator from math import * from exprParser import * parser = ExprParser() def plotFunction( f, xmin = -8., xmax = 8., ymin = -6., ymax = 6., pictureWidth_cm = 16., dpi = 100 ): fig = plt.figure() aspect = (ymax - ymin)/(xmax - xmin) pictureHeight_cm = pictureWidth_cm*aspect fig.set_size_inches(pictureWidth_cm/2.54, pictureHeight_cm/2.54) fig.set_dpi(dpi) ax = fig.add_subplot(1, 1, 1) ax.set_aspect(1.) ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) ax.xaxis.set_major_locator(MultipleLocator(5)) ax.xaxis.set_minor_locator(AutoMinorLocator(5)) ax.yaxis.set_major_locator(MultipleLocator(5)) ax.yaxis.set_minor_locator(AutoMinorLocator(5)) ax.axhline(0, color="black") ax.axvline(0, color="black") ax.grid(which='major') ax.grid(which='minor', linestyle=":") x = [] y = [] xx = xmin dx = (xmax - xmin)/1000 yCenter = (ymin + ymax)/2. dy = abs(ymax - ymin) yMinBorder = yCenter - dy*0.75 yMaxBorder = yCenter + dy*0.75 while xx <= xmax: try: yy = f(xx) if yy > yMaxBorder: yy = inf elif yy < yMinBorder: yy = -inf except Exception: yy = None x.append(xx) y.append(yy) xx += dx ax.plot(x, y) plt.show() def plotExpression( funcText, xmin = -8., xmax = 8., ymin = -6., ymax = 6., pictureWidth_cm = 16. ): try: parser.parse(funcText) plotFunction( parserFunction, xmin, xmax, ymin, ymax, pictureWidth_cm ) except SyntaxError as e: print("Parse error: " + str(e)) def parserFunction(x): return parser.evaluate(x) def main(): while True: f = input("Input a function: "); if f == "": break; try: plotExpression(f) except SyntaxError as e: print("Syntax error: " + str(e)) if __name__ == "__main__": main()