ZZYZZY_01
2022-01-15 20:25
采纳率: 100%
浏览 25
已结题

sympy.sympify转化字符串为表达式的问题

我在sympify转化10sin(t)一类的字符串时,转化的结果不是10sympy.sin(t)而是10*sin(t),导致接下来赋值运算报错
TypeError: can't convert expression to float
如何才能输入sin(t),转化为sympy.sin(t) ?

部分代码:


```python
def Equation(input):
    global change_barrier_switch, nbarrier, start_start
    print(input)
    start_start = False
    nbarrier = numpy.zeros((height, width), bool)
    x, y, t = sympy.symbols("x y t", real=True)
    st = -200
    ed = -st
    # Ex = 10 * sympy.sin(t)
    Ex = sympy.sympify(input, evaluate=False)
    print(Ex)  # 如果输入"10*sin(t)"这个打印内容为"10*sin(t)"
    Ey = 10 * sympy.cos(t)
    '''
    # Ex = 16 * ((sympy.sin(t)) ** 3)
    # Ey = 13 * sympy.cos(t) - 5 * sympy.cos(2 * t) - 2 * sympy.cos(3 * t) - sympy.cos(4 * t)
    '''
    for tent in range(10 * st, 10 * ed, 1):
        nt = tent / 10
        x = int(round(Ex.subs(t, nt)) + height / 2)  #这里因为转化成了"10*sin(t)"而报错 TypeError: can't convert expression to float
        y = int(round(Ey.subs(t, nt)) + height / 2)
        nbarrier[y, x] = True
    change_barrier_switch = True
    start_start = True


switch_eq = True


def HelpEquation():
    global switch_eq
    if switch_eq:
        equation_window = Tkinter.Toplevel(control_window)
        equation_window.geometry('300x220')
        Labal_x = Tkinter.Label(equation_window, text="x=")
        Labal_x.pack(side=Tkinter.LEFT)
        Entry_x = Tkinter.Entry(equation_window, width=40)
        Entry_x.pack(side=Tkinter.RIGHT)
        EqButton = Tkinter.Button(equation_window, text='确定', width=5, height=1, command=lambda: Equation(Entry_x.get())) #输入表达式字符串 例如“10*sin(t)"
        EqButton.place(x=100, y=150)


  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • CSDN专家-HGJ 2022-01-15 23:55
    最佳回答

    1.第12行用eval函数执行字符表达式并返回其值。.
    Ex = sympy.sympify(eval(input),evaluate=False)
    2.Entry输入框在输入时,写成:
    10 * sympy.sin(t)
    这样试试。

    评论
    解决 1 无用
    打赏 举报

相关推荐 更多相似问题