用一个输出单元编程一个函数

2024-06-07 12:55:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着写一个需要输入多项式函数的代码,然后将输入结果转换成Latex,这是我的问题。这是我的代码有什么建议吗?你知道吗

#%%
import sympy as sp
def f():
       f= eval(input("Enter your polynominal based function: "))
       return f
x = sp.Symbol('x')
f = f()
derivative = sp.diff(f,x)
statement = 'This is the derivative of '
statement1 = str(f) 
statement2 = ' which is '
statement3 = str(derivative)
overallStatement = statement + statement1 + statement2 + statement3
sp.latex(overallStatement)
#%%

Tags: 函数代码importissp建议latexstatement
1条回答
网友
1楼 · 发布于 2024-06-07 12:55:32

您需要的是在sympy上下文中解析一个字符串,这是任何一个像样的计算机代数系统(CAS)提供的工具。看看sympify函数。粗略示例(py 2.7)如下所示:

import sympy as sp

pol = raw_input("Enter polynomial: ")
p = sp.sympify(pol)
dpdx = p.diff()

print "f(x) : " + sp.latex(p)
print "f'(x): " + sp.latex(dpdx)
print "g(x) : " + sp.latex(p + dpdx)
# Enter polynomial: x**2
# f(x) : x^{2}
# f'(x) : 2 x
# g(x) : x^{2} + 2 x

相关问题 更多 >

    热门问题