尝试创建函数Grapher时出错

时间:2018-02-02 15:44:46

标签: python numpy matplotlib sympy

我正在尝试使用Python创建一个程序,允许用户选择一个函数并将其绘制在指定值上。我有这个:

import matplotlib.pyplot as plt
import math
import numpy as np
from sympy import Symbol, Derivative, sin, sympify
from sympy.core.sympify import SympifyError

x = Symbol('x')

fx = sympify(input("What is your function? "))
x_min = float(input("Enter x minimum: "))
x_max = float(input("Enter x maximum: "))

x_values = np.linspace(x_min, x_max, 3)
y_values = fx.doit().subs({x:x_values})

plt.plot(x_values, y_values)

plt.show()

我为函数输入x ** 2,为x_min输入0,为x_max输入3。我得到的错误是:

Traceback (most recent call last):
  File 
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sympy/core/sympify.py", line 178, in sympify
expr = parse_expr(a, locals or {}, rational, convert_xor)
  File 
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sympy/parsing/sympy_parser.py", line 163, in parse_expr
expr = eval(code, global_dict, local_dict) # take local objects in preference
  File "<string>", line 1
    [Float ('0.' )Float ('1.5' )Float ('3.' )]
                  ^
SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/joe126/Dropbox/Python/Chapter02.py", line 16, in <module>
  File 
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sympy/core/basic.py", line 831, in subs
so, sn = sympify(o), sympify(n)
  File 
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sympy/core/sympify.py", line 180, in sympify
raise SympifyError('could not parse %r' % a)
sympy.core.sympify.SympifyError: SympifyError: "could not parse '[0.  1.5 3. ]'"

出了什么问题?感谢。

1 个答案:

答案 0 :(得分:3)

我无法重现错误。我得到了与Georgy相同的错误:绘图时形状不匹配。但是你为什么不尝试使用lambdify来评估这个函数:

import matplotlib.pyplot as plt
import math
import numpy as np
from sympy import Symbol, Derivative, sin, sympify, lambdify
from sympy.core.sympify import SympifyError

x = Symbol('x')

fx = sympify(input("What is your function? "))
x_min = float(input("Enter x minimum: "))
x_max = float(input("Enter x maximum: "))

x_values = np.linspace(x_min, x_max, 3)
fx_lambda = lambdify(x,fx)
y_values = fx_lambda(x_values)

plt.plot(x_values, y_values)

plt.show()

Result for x**2 from 0 to 3