简体   繁体   English

如何根据用户输入在 SymPy 中创建符号?

[英]How do I create Symbols in SymPy based on user input?

I am trying to create a python programme that takes a function from the user (in terms of x) and returns its derivative using SymPy.我正在尝试创建一个 python 程序,它从用户那里获取一个函数(就 x 而言)并使用 SymPy 返回它的导数。 However, when I enter letters other than x, SymPy throws an error of undefined symbols.但是,当我输入 x 以外的字母时,SymPy 会抛出未定义符号的错误。 I want it to treat letters apart from x as constant.我希望它将除 x 之外的字母视为常量。

For example, if a user enters a*x**2 + bx , they should get 2*a*x + b , and if they enter z*x**2 + px , they should get 2*z*x + p .例如,如果用户输入a*x**2 + bx ,他们应该得到2*a*x + b ,如果他们输入z*x**2 + px ,他们应该得到2*z*x + p . How can I treat letters apart from 'x' as constants without having to hard-code every letter as a symbol?如何将除“x”之外的字母视为常量,而不必将每个字母硬编码为符号?

I hope my question is clear.我希望我的问题很清楚。 Feel free to ask for any clarifications if required.如果需要,请随时要求任何说明。

You should first parse the user input and collect all symbols.您应该首先解析用户输入并收集所有符号。 To parse string to sympy expression use sympy.sympify .要将字符串解析为 sympy 表达式,请使用sympy.sympify I assume you want to get derivative only WRT x.我假设您只想获得 WRT x 的导数。 The full code will be:完整的代码将是:

import sympy as sp
expr = sp.sympify(input('enter expression: '))
print('Derivative w.r.t x: ', sp.diff(expr, 'x'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建一个功能,该功能可以创建列表并根据用户输入将成员添加到这些列表中? - How do i create a function that creates list and adds members to those list based on user input? 如何根据用户输入在我的 pyGame 中创建 2 到 4 个玩家? - How do I create between 2 and 4 players in my pyGame based on user input? 如何根据用户的输入创建多个密码生成器? - How do I create multiple password generator based on user's input? 如何根据用户输入创建不同数量的条目小部件 - How do I create different number of entry widgets based on user input 如何根据用户输入创建变量? (Python) - How do you create variables based on user input? (Python) 我如何创建一个函数,该函数根据在Python中输入相同输入的次数,使用户输入具有不同的结果? - How do I create a function that allows for user input to have a different outcomes based on how many times the same input was entered in Python? 如何让 Sympy 解析表达式,同时仅将任意先前定义的字符串视为符号? - How do I let Sympy parse an expression while only regarding arbitrary previously defined strings as symbols? 如何创建具有相同名称的两个不同的 sympy 符号 - How to create two different sympy symbols with the same name 如何根据用户输入显示CSV数据? - How do I display data from CSV based on user input? "如何根据用户输入重新启动程序?" - How do I restart a program based on user input?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM