印刷#
见 Printing 教程中介绍打印的部分。
本指南记录了SymPy中的打印系统及其内部工作原理。
打印机类#
打印子系统驱动程序
SymPy的打印系统的工作方式如下:任何表达式都可以传递给指定的打印机,然后由指定的打印机负责返回该表达式的适当表示形式。
基本概念如下:
如果对象知道如何打印,就让它自己打印。
采用打印机中定义的最佳拟合方法。
作为回退,对打印机使用emptyPrinter方法。
哪种方法负责打印?#
整个打印过程通过调用 .doprint(expr) 在您要使用的打印机上。此方法寻找一个合适的方法,该方法可以按打印机定义的给定样式打印给定表达式。在寻找方法时,它遵循以下步骤:
如果对象知道如何打印,就让它自己打印。
打印机在每个对象中查找特定方法。该方法的名称取决于特定打印机,并在下定义
Printer.printmethod. 例如,StrPrinter调用_sympystr以及最新的打印机呼叫_latex. 查看要使用的打印机的文档。方法的名称在那里指定。This was the original way of doing printing in sympy. Every class had its own latex, mathml, str and repr methods, but it turned out that it is hard to produce a high quality printer, if all the methods are spread out that far. Therefore all printing code was combined into the different printers, which works great for built-in SymPy objects, but not that good for user defined classes where it is inconvenient to patch the printers.
采用打印机中定义的最佳拟合方法。
打印机循环遍历expr类(class+其基),并尝试将工作分派到
_print_<EXPR_CLASS>e、 g.假设我们有下面的类层次结构:
Basic | Atom | Number | Rational
那么,为了
expr=Rational(...),打印机将尝试按下图所示顺序调用打印机方法:p._print(expr) | |-- p._print_Rational(expr) | |-- p._print_Number(expr) | |-- p._print_Atom(expr) | `-- p._print_Basic(expr)
如果
._print_Rational方法存在于打印机中,然后调用它,并返回结果。否则,打印机将尝试调用._print_Number等等。As a fall-back use the emptyPrinter method for the printer.
作为退后
self.emptyPrinter将使用表达式调用。如果未在Printer子类中定义,则与str(expr).
自定义打印机示例#
在下面的例子中,我们有一台打印机,它以较短的形式打印函数的导数。
from sympy.core.symbol import Symbol
from sympy.printing.latex import LatexPrinter, print_latex
from sympy.core.function import UndefinedFunction, Function
class MyLatexPrinter(LatexPrinter):
"""Print derivative of a function of symbols in a shorter form.
"""
def _print_Derivative(self, expr):
function, *vars = expr.args
if not isinstance(type(function), UndefinedFunction) or \
not all(isinstance(i, Symbol) for i in vars):
return super()._print_Derivative(expr)
# If you want the printer to work correctly for nested
# expressions then use self._print() instead of str() or latex().
# See the example of nested modulo below in the custom printing
# method section.
return "{}_{{{}}}".format(
self._print(Symbol(function.func.__name__)),
''.join(self._print(i) for i in vars))
def print_my_latex(expr):
""" Most of the printers define their own wrappers for print().
These wrappers usually take printer settings. Our printer does not have
any settings.
"""
print(MyLatexPrinter().doprint(expr))
y = Symbol("y")
x = Symbol("x")
f = Function("f")
expr = f(x, y).diff(x, y)
# Print the expression using the normal latex printer and our custom
# printer.
print_latex(expr)
print_my_latex(expr)
以上代码的输出为:
\frac{\partial^{2}}{\partial x\partial y} f{\left(x,y \right)}
f_{xy}
自定义打印方法示例#
在下面的示例中,修改了模运算符的 Latex 打印。这是通过重写方法来完成的 _latex 属于 Mod .
>>> from sympy import Symbol, Mod, Integer, print_latex
>>> # Always use printer._print()
>>> class ModOp(Mod):
... def _latex(self, printer):
... a, b = [printer._print(i) for i in self.args]
... return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b)
将自定义运算符与内置运算符的输出进行比较:
>>> x = Symbol('x')
>>> m = Symbol('m')
>>> print_latex(Mod(x, m))
x \bmod m
>>> print_latex(ModOp(x, m))
\operatorname{Mod}{\left(x, m\right)}
常见错误#
始终使用 self._print(obj) 在自定义打印机时打印表达式的子组件。错误包括:
使用
self.doprint(obj)而是:>>> # This example does not work properly, as only the outermost call may use >>> # doprint. >>> class ModOpModeWrong(Mod): ... def _latex(self, printer): ... a, b = [printer.doprint(i) for i in self.args] ... return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b)
This fails when the
modeargument is passed to the printer:>>> print_latex(ModOp(x, m), mode='inline') # ok $\operatorname{Mod}{\left(x, m\right)}$ >>> print_latex(ModOpModeWrong(x, m), mode='inline') # bad $\operatorname{Mod}{\left($x$, $m$\right)}$
使用
str(obj)而是:>>> class ModOpNestedWrong(Mod): ... def _latex(self, printer): ... a, b = [str(i) for i in self.args] ... return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b)
这在嵌套对象上失败:
>>> # Nested modulo. >>> print_latex(ModOp(ModOp(x, m), Integer(7))) # ok \operatorname{Mod}{\left(\operatorname{Mod}{\left(x, m\right)}, 7\right)} >>> print_latex(ModOpNestedWrong(ModOpNestedWrong(x, m), Integer(7))) # bad \operatorname{Mod}{\left(ModOpNestedWrong(x, m), 7\right)}
使用
LatexPrinter()._print(obj)相反。>>> from sympy.printing.latex import LatexPrinter >>> class ModOpSettingsWrong(Mod): ... def _latex(self, printer): ... a, b = [LatexPrinter()._print(i) for i in self.args] ... return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b)
这将导致放弃子对象中的所有设置。例如
full_prec忽略将浮动显示为全精度的设置:>>> from sympy import Float >>> print_latex(ModOp(Float(1) * x, m), full_prec=True) # ok \operatorname{Mod}{\left(1.00000000000000 x, m\right)} >>> print_latex(ModOpSettingsWrong(Float(1) * x, m), full_prec=True) # bad \operatorname{Mod}{\left(1.0 x, m\right)}
负责打印的主要类是 Printer (另见its source code ):
PretyPrinter类#
漂亮打印子系统在中实现 sympy.printing.pretty.pretty 由 PrettyPrinter 类派生自 Printer . 它依赖于模块 sympy.printing.pretty.stringPict 和 sympy.printing.pretty.pretty_symbology 用于渲染美观的公式。
模块 stringPict 提供基类 stringPict 以及派生类 prettyForm 这可以简化跨越多条线的公式的创建和操作。
模块 pretty_symbology 提供基本体来构造二维形状(hline、vline等),以及在可能的情况下自动使用unicode的技术。
- class sympy.printing.pretty.pretty.PrettyPrinter(settings=None)[源代码]#
打印机,它将表达式转换为二维ASCII图形。
- printmethod: str = '_pretty'#
- sympy.printing.pretty.pretty.pretty(expr, *, order=None, full_prec='auto', use_unicode=True, wrap_line=False, num_columns=None, use_unicode_sqrt_char=True, root_notation=True, mat_symbol_style='plain', imaginary_unit='i', perm_cyclic=True)#
返回一个字符串,该字符串包含经过修饰的expr格式。
有关关键字参数的信息,请参阅prettyu print函数。
- sympy.printing.pretty.pretty.pretty_print(expr, **kwargs)[源代码]#
以漂亮的形式打印表达式。
pprint只是这个函数的一个快捷方式。
- 参数:
expr :表达式
要打印的表达式。
wrap_line :bool,可选(默认值=True)
启用/禁用换行。
num_columns :int或None,可选(默认值=None)
换行前的列数(默认为None,读取终端宽度),在使用不带终端的SymPy时很有用。
use_unicode :bool或None,可选(默认值=None)
使用unicode字符,例如希腊字母pi而不是字符串pi。
full_prec :bool或string,可选(默认=“auto”)
使用完全精确。
秩序 :bool或string,可选(默认值=无)
如果很慢,则将长表达式设置为“无”;默认值为“无”。
use_unicode_sqrt_char :bool,可选(默认值=True)
使用紧凑的单字符平方根符号(当不含糊时)。
root_notation :bool,可选(默认值=True)
设置为'False'以打印分数形式1/n的指数。默认情况下,指数以根形式打印。
mat_symbol_style :string,可选(默认=“普通”)
设置为“粗体”以使用粗体数学符号面打印矩阵符号。默认情况下使用标准面。
imaginary_unit :string,可选(默认值=“i”)
当use_unicode为真时用于虚单位的字母。可以是“i”(默认)或“j”。
C代码打印机#
这个类实现C代码打印,也就是说,它将Python表达式转换为C代码的字符串(另请参见 C89CodePrinter )
用法:
>>> from sympy.printing import print_ccode
>>> from sympy.functions import sin, cos, Abs, gamma
>>> from sympy.abc import x
>>> print_ccode(sin(x)**2 + cos(x)**2, standard='C89')
pow(sin(x), 2) + pow(cos(x), 2)
>>> print_ccode(2*x + cos(x), assign_to="result", standard='C89')
result = 2*x + cos(x);
>>> print_ccode(Abs(x**2), standard='C89')
fabs(pow(x, 2))
>>> print_ccode(gamma(x**2), standard='C99')
tgamma(pow(x, 2))
- sympy.printing.c.known_functions_C89 = {'Abs': [(<function <lambda>>, 'fabs'), (<function <lambda>>, 'abs')], 'acos': 'acos', 'asin': 'asin', 'atan': 'atan', 'atan2': 'atan2', 'ceiling': 'ceil', 'cos': 'cos', 'cosh': 'cosh', 'exp': 'exp', 'floor': 'floor', 'log': 'log', 'sin': 'sin', 'sinh': 'sinh', 'sqrt': 'sqrt', 'tan': 'tan', 'tanh': 'tanh'}#
- sympy.printing.c.known_functions_C99 = {'Abs': [(<function <lambda>>, 'fabs'), (<function <lambda>>, 'abs')], 'Cbrt': 'cbrt', 'Max': 'fmax', 'Min': 'fmin', 'acos': 'acos', 'acosh': 'acosh', 'asin': 'asin', 'asinh': 'asinh', 'atan': 'atan', 'atan2': 'atan2', 'atanh': 'atanh', 'ceiling': 'ceil', 'cos': 'cos', 'cosh': 'cosh', 'erf': 'erf', 'erfc': 'erfc', 'exp': 'exp', 'exp2': 'exp2', 'expm1': 'expm1', 'floor': 'floor', 'fma': 'fma', 'gamma': 'tgamma', 'hypot': 'hypot', 'log': 'log', 'log10': 'log10', 'log1p': 'log1p', 'log2': 'log2', 'loggamma': 'lgamma', 'sin': 'sin', 'sinh': 'sinh', 'sqrt': 'sqrt', 'tan': 'tan', 'tanh': 'tanh'}#
- class sympy.printing.c.C89CodePrinter(settings=None)[源代码]#
A printer to convert Python expressions to strings of C code
- printmethod: str = '_ccode'#
- sympy.printing.c.ccode(expr, assign_to=None, standard='c99', **settings)[源代码]#
将表达式转换为c代码字符串
- 参数:
expr :表达式
A SymPy expression to be converted.
assign_to :可选
当给定参数时,参数将用作表达式分配给的变量的名称。可以是字符串,
Symbol,MatrixSymbol或Indexed类型。这对于换行或生成多行语句的表达式非常有用。标准 :str,可选
指定标准的字符串。如果编译器支持更现代的标准,可以将其设置为“c99”,以允许打印机使用更多的数学函数。 [default='c89'] .
精度 :整数,可选
像pi这样的数字的精度 [default=17] .
user_functions :dict,可选
一种字典,其中的键是
FunctionClass或UndefinedFunction实例和值是它们所需的C字符串表示形式。或者,字典值可以是元组的列表,即。 [(argument_test, cfunction_string)] 或 [(argument_test, cfunction_formater)] . 示例见下文。撤销引用 :iterable,可选
在打印的代码表达式中应该被取消引用的一种符号。这些值将通过地址传递给函数。例如,如果
dereference=[a],生成的代码将打印出来(*a)而不是a.人类 :bool,可选
如果为True,则结果为单个字符串,其中可能包含数字符号的某些常量声明。如果为False,则在元组中返回相同的信息(symbols_to_declare,不支持_functions,code_text)。 [default=True] .
合同:bool,可选
如果属实,
Indexed假设实例服从张量收缩规则,并在索引上生成相应的嵌套循环。设置contract=False不会生成循环,相反,用户负责为代码中的索引提供值。 [default=True] .
实例
>>> from sympy import ccode, symbols, Rational, sin, ceiling, Abs, Function >>> x, tau = symbols("x, tau") >>> expr = (2*tau)**Rational(7, 2) >>> ccode(expr) '8*M_SQRT2*pow(tau, 7.0/2.0)' >>> ccode(expr, math_macros={}) '8*sqrt(2)*pow(tau, 7.0/2.0)' >>> ccode(sin(x), assign_to="s") 's = sin(x);' >>> from sympy.codegen.ast import real, float80 >>> ccode(expr, type_aliases={real: float80}) '8*M_SQRT2l*powl(tau, 7.0L/2.0L)'
Simple custom printing can be defined for certain types by passing a dictionary of {"type" : "function"} to the
user_functionskwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)].>>> custom_functions = { ... "ceiling": "CEIL", ... "Abs": [(lambda x: not x.is_integer, "fabs"), ... (lambda x: x.is_integer, "ABS")], ... "func": "f" ... } >>> func = Function('func') >>> ccode(func(Abs(x) + ceiling(x)), standard='C89', user_functions=custom_functions) 'f(fabs(x) + CEIL(x))'
或者如果C函数接受原始参数的子集:
>>> ccode(2**x + 3**x, standard='C99', user_functions={'Pow': [ ... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e), ... (lambda b, e: b != 2, 'pow')]}) 'exp2(x) + pow(3, x)'
Piecewise表达式被转换成条件句。如果assign_to变量提供一个if语句,否则使用三元运算符。注意如果Piecewise缺少默认术语,表示为(expr, True)然后抛出一个错误。这是为了防止生成一个可能无法计算任何结果的表达式。>>> from sympy import Piecewise >>> expr = Piecewise((x + 1, x > 0), (x, True)) >>> print(ccode(expr, tau, standard='C89')) if (x > 0) { tau = x + 1; } else { tau = x; }
对循环的支持通过
Indexed类型。与contract=True这些表达式将变成循环,而contract=False将只打印应该循环的赋值表达式:>>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> ccode(e.rhs, assign_to=e.lhs, contract=False, standard='C89') 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
也支持矩阵,但是
MatrixSymbol必须提供相同尺寸的assign_to. 也可以在正常情况下生成的矩阵中存在:>>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) >>> A = MatrixSymbol('A', 3, 1) >>> print(ccode(mat, A, standard='C89')) A[0] = pow(x, 2); if (x > 0) { A[1] = x + 1; } else { A[1] = x; } A[2] = sin(x);
C++代码打印机#
这个模块包含C++代码的打印机,即将SCORY表达式转换为C++代码串的函数。
用法:
>>> from sympy.printing import cxxcode
>>> from sympy.functions import Min, gamma
>>> from sympy.abc import x
>>> print(cxxcode(Min(gamma(x) - 1, x), standard='C++11'))
std::min(x, std::tgamma(x) - 1)
RCodePrinter#
这个类实现R代码打印(即,它将Python表达式转换为R代码的字符串)。
用法:
>>> from sympy.printing import print_rcode
>>> from sympy.functions import sin, cos, Abs
>>> from sympy.abc import x
>>> print_rcode(sin(x)**2 + cos(x)**2)
sin(x)^2 + cos(x)^2
>>> print_rcode(2*x + cos(x), assign_to="result")
result = 2*x + cos(x);
>>> print_rcode(Abs(x**2))
abs(x^2)
- sympy.printing.rcode.known_functions = {'Abs': 'abs', 'Max': 'max', 'Min': 'min', 'acos': 'acos', 'acosh': 'acosh', 'asin': 'asin', 'asinh': 'asinh', 'atan': 'atan', 'atan2': 'atan2', 'atanh': 'atanh', 'beta': 'beta', 'ceiling': 'ceiling', 'cos': 'cos', 'cosh': 'cosh', 'digamma': 'digamma', 'erf': 'erf', 'exp': 'exp', 'factorial': 'factorial', 'floor': 'floor', 'gamma': 'gamma', 'log': 'log', 'sign': 'sign', 'sin': 'sin', 'sinh': 'sinh', 'sqrt': 'sqrt', 'tan': 'tan', 'tanh': 'tanh', 'trigamma': 'trigamma'}#
- class sympy.printing.rcode.RCodePrinter(settings={})[源代码]#
A printer to convert SymPy expressions to strings of R code
- printmethod: str = '_rcode'#
- sympy.printing.rcode.rcode(expr, assign_to=None, **settings)[源代码]#
将表达式转换为r代码字符串
- 参数:
expr :表达式
A SymPy expression to be converted.
assign_to :可选
当给定参数时,参数将用作表达式分配给的变量的名称。可以是字符串,
Symbol,MatrixSymbol或Indexed类型。这对于换行或生成多行语句的表达式非常有用。精度 :整数,可选
像pi这样的数字的精度 [default=15] .
user_functions :dict,可选
一种字典,其中的键是
FunctionClass或UndefinedFunction实例和值是它们所需的R字符串表示形式。或者,字典值可以是元组的列表,即。 [(argument_test, rfunction_string)] 或 [(argument_test, rfunction_formater)] . 示例见下文。人类 :bool,可选
如果为True,则结果为单个字符串,其中可能包含数字符号的某些常量声明。如果为False,则在元组中返回相同的信息(symbols_to_declare,不支持_functions,code_text)。 [default=True] .
合同:bool,可选
如果属实,
Indexed假设实例服从张量收缩规则,并在索引上生成相应的嵌套循环。设置contract=False不会生成循环,相反,用户负责为代码中的索引提供值。 [default=True] .
实例
>>> from sympy import rcode, symbols, Rational, sin, ceiling, Abs, Function >>> x, tau = symbols("x, tau") >>> rcode((2*tau)**Rational(7, 2)) '8*sqrt(2)*tau^(7.0/2.0)' >>> rcode(sin(x), assign_to="s") 's = sin(x);'
Simple custom printing can be defined for certain types by passing a dictionary of {"type" : "function"} to the
user_functionskwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)].>>> custom_functions = { ... "ceiling": "CEIL", ... "Abs": [(lambda x: not x.is_integer, "fabs"), ... (lambda x: x.is_integer, "ABS")], ... "func": "f" ... } >>> func = Function('func') >>> rcode(func(Abs(x) + ceiling(x)), user_functions=custom_functions) 'f(fabs(x) + CEIL(x))'
或者如果R函数接受原始参数的子集:
>>> rcode(2**x + 3**x, user_functions={'Pow': [ ... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e), ... (lambda b, e: b != 2, 'pow')]}) 'exp2(x) + pow(3, x)'
Piecewise表达式被转换成条件句。如果assign_to变量提供一个if语句,否则使用三元运算符。注意如果Piecewise缺少默认术语,表示为(expr, True)然后抛出一个错误。这是为了防止生成一个可能无法计算任何结果的表达式。>>> from sympy import Piecewise >>> expr = Piecewise((x + 1, x > 0), (x, True)) >>> print(rcode(expr, assign_to=tau)) tau = ifelse(x > 0,x + 1,x);
对循环的支持通过
Indexed类型。与contract=True这些表达式将变成循环,而contract=False将只打印应该循环的赋值表达式:>>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> rcode(e.rhs, assign_to=e.lhs, contract=False) 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
也支持矩阵,但是
MatrixSymbol必须提供相同尺寸的assign_to. 也可以在正常情况下生成的矩阵中存在:>>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) >>> A = MatrixSymbol('A', 3, 1) >>> print(rcode(mat, A)) A[0] = x^2; A[1] = ifelse(x > 0,x + 1,x); A[2] = sin(x);
Fortran打印#
这个 fcode 函数将sympy表达式转换为Fortran代码。主要目的是减轻手动翻译长数学表达式的负担。因此,生成的表达式也不需要(或很少)手动调整即可使其可编译。的可选参数 fcode 可以用来微调 fcode 这样就不再需要手动更改结果了。
- sympy.printing.fortran.fcode(expr, assign_to=None, **settings)[源代码]#
将表达式转换为fortran代码的字符串
- 参数:
expr :表达式
A SymPy expression to be converted.
assign_to :可选
当给定参数时,参数将用作表达式分配给的变量的名称。可以是字符串,
Symbol,MatrixSymbol或Indexed类型。这对于换行或生成多行语句的表达式非常有用。精度 :整数,可选
已弃用。请改用u类型的映射。像pi这样的数字的精度 [default=17] .
user_functions :dict,可选
有钥匙的词典
FunctionClass实例和值是它们的字符串表示。或者,字典值可以是元组的列表,即。 [(argument_test, cfunction_string)] . 示例见下文。人类 :bool,可选
如果为True,则结果为单个字符串,其中可能包含数字符号的某些常量声明。如果为False,则在元组中返回相同的信息(symbols_to_declare,不支持_functions,code_text)。 [default=True] .
合同:bool,可选
如果属实,
Indexed假设实例服从张量收缩规则,并在索引上生成相应的嵌套循环。设置contract=False不会生成循环,相反,用户负责为代码中的索引提供值。 [default=True] .source_format :可选
源格式可以是“fixed”或“free”。 [default='fixed']
标准 :整数,可选
要遵循的Fortran标准。它被指定为整数。可接受的标准是66、77、90、95、2003和2008。默认值为77。注意,目前内部唯一的区别是95年以前的标准和95年以后的标准。这可能会在以后随着更多功能的添加而改变。
name_mangling :bool,可选
If True, then the variables that would become identical in case-insensitive Fortran are mangled by appending different number of
_at the end. If False, SymPy Will not interfere with naming of variables. [default=True]
实例
>>> from sympy import fcode, symbols, Rational, sin, ceiling, floor >>> x, tau = symbols("x, tau") >>> fcode((2*tau)**Rational(7, 2)) ' 8*sqrt(2.0d0)*tau**(7.0d0/2.0d0)' >>> fcode(sin(x), assign_to="s") ' s = sin(x)'
通过将“type”:“function”字典传递给
user_functions夸克。或者,字典值可以是元组的列表,即。 [(argument_test, cfunction_string)] .>>> custom_functions = { ... "ceiling": "CEIL", ... "floor": [(lambda x: not x.is_integer, "FLOOR1"), ... (lambda x: x.is_integer, "FLOOR2")] ... } >>> fcode(floor(x) + ceiling(x), user_functions=custom_functions) ' CEIL(x) + FLOOR1(x)'
Piecewise表达式被转换成条件句。如果assign_to变量提供一个if语句,否则使用三元运算符。注意如果Piecewise缺少默认术语,表示为(expr, True)然后抛出一个错误。这是为了防止生成一个可能无法计算任何结果的表达式。>>> from sympy import Piecewise >>> expr = Piecewise((x + 1, x > 0), (x, True)) >>> print(fcode(expr, tau)) if (x > 0) then tau = x + 1 else tau = x end if
对循环的支持通过
Indexed类型。与contract=True这些表达式将变成循环,而contract=False将只打印应该循环的赋值表达式:>>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> fcode(e.rhs, assign_to=e.lhs, contract=False) ' Dy(i) = (y(i + 1) - y(i))/(t(i + 1) - t(i))'
也支持矩阵,但是
MatrixSymbol必须提供相同尺寸的assign_to. 也可以在正常情况下生成的矩阵中存在:>>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) >>> A = MatrixSymbol('A', 3, 1) >>> print(fcode(mat, A)) A(1, 1) = x**2 if (x > 0) then A(2, 1) = x + 1 else A(2, 1) = x end if A(3, 1) = sin(x)
- class sympy.printing.fortran.FCodePrinter(settings=None)[源代码]#
A printer to convert SymPy expressions to strings of Fortran code
- printmethod: str = '_fcode'#
两个基本示例:
>>> from sympy import *
>>> x = symbols("x")
>>> fcode(sqrt(1-x**2))
' sqrt(1 - x**2)'
>>> fcode((3 + 4*I)/(1 - conjugate(x)))
' (cmplx(3,4))/(1 - conjg(x))'
需要换行的示例:
>>> expr = sqrt(1-x**2).series(x,n=20).removeO()
>>> print(fcode(expr))
-715.0d0/65536.0d0*x**18 - 429.0d0/32768.0d0*x**16 - 33.0d0/
@ 2048.0d0*x**14 - 21.0d0/1024.0d0*x**12 - 7.0d0/256.0d0*x**10 -
@ 5.0d0/128.0d0*x**8 - 1.0d0/16.0d0*x**6 - 1.0d0/8.0d0*x**4 - 1.0d0
@ /2.0d0*x**2 + 1
在行换行的情况下,包含赋值是很方便的,这样当添加赋值部分时,就可以正确地换行了。
>>> print(fcode(expr, assign_to="var"))
var = -715.0d0/65536.0d0*x**18 - 429.0d0/32768.0d0*x**16 - 33.0d0/
@ 2048.0d0*x**14 - 21.0d0/1024.0d0*x**12 - 7.0d0/256.0d0*x**10 -
@ 5.0d0/128.0d0*x**8 - 1.0d0/16.0d0*x**6 - 1.0d0/8.0d0*x**4 - 1.0d0
@ /2.0d0*x**2 + 1
对于分段函数 assign_to 选项是必需的:
>>> print(fcode(Piecewise((x,x<1),(x**2,True)), assign_to="var"))
if (x < 1) then
var = x
else
var = x**2
end if
注意,由于Fortran 77中缺少条件运算符,默认情况下只支持顶级分段函数。可以使用 merge 在Fortran 95中通过设置kwarg standard=95 :
>>> print(fcode(Piecewise((x,x<1),(x**2,True)), standard=95))
merge(x, x**2, x < 1)
如果表达式中有索引对象,则生成循环。这还需要使用assign_to选项。
>>> A, B = map(IndexedBase, ['A', 'B'])
>>> m = Symbol('m', integer=True)
>>> i = Idx('i', m)
>>> print(fcode(2*B[i], assign_to=A[i]))
do i = 1, m
A(i) = 2*B(i)
end do
带有索引对象的表达式中的重复索引被解释为求和。例如,可以使用
>>> print(fcode(A[i, i], assign_to=x))
x = 0
do i = 1, m
x = x + A(i, i)
end do
默认情况下,对符号进行编号,例如 pi 和 E 被检测并定义为Fortran参数。常量的精度可以通过precision参数进行调整。使用 N 功能。
>>> print(fcode(x - pi**2 - E))
parameter (E = 2.7182818284590452d0)
parameter (pi = 3.1415926535897932d0)
x - pi**2 - E
>>> print(fcode(x - pi**2 - E, precision=25))
parameter (E = 2.718281828459045235360287d0)
parameter (pi = 3.141592653589793238462643d0)
x - pi**2 - E
>>> print(fcode(N(x - pi**2, 25)))
x - 9.869604401089358618834491d0
当某些函数不是Fortran标准的一部分时,最好在Fortran表达式中引入用户定义函数的名称。
>>> print(fcode(1 - gamma(x)**2, user_functions={'gamma': 'mygamma'}))
1 - mygamma(x)**2
However, when the user_functions argument is not provided, fcode will
by default raise an Exception, but if the user intends to provide a function
with the same name, code can still be generated, by passing the option
strict=False. The code then contains a comment informing the user of the issue:
>>> print(fcode(1 - gamma(x)**2, strict=False))
C Not supported in Fortran:
C gamma
1 - gamma(x)**2
打印机可以配置为忽略这些注释:
>>> print(fcode(1 - gamma(x)**2, allow_unknown_functions=True))
1 - gamma(x)**2
默认情况下,输出是人类可读的代码,可以进行复制和粘贴。有选择权 human=False ,返回值适用于使用编写带有多条指令的例程的源代码生成器进行后处理。返回值是一个三元组,它包含:(i)必须定义为“Fortran参数”的一组数字符号;(ii)不能用纯Fortran语言翻译的列表函数;(iii)Fortran代码的字符串。几个例子:
>>> fcode(1 - gamma(x)**2, human=False)
(set(), {gamma(x)}, ' 1 - gamma(x)**2')
>>> fcode(1 - sin(x)**2, human=False)
(set(), set(), ' 1 - sin(x)**2')
>>> fcode(x - pi**2, human=False)
({(pi, '3.1415926535897932d0')}, set(), ' x - pi**2')
SMT-Lib printing#
- class sympy.printing.smtlib.SMTLibPrinter(settings: dict | None = None, symbol_table=None)[源代码]#
- printmethod: str = '_smtlib'#
- _default_settings: dict = {'known_constants': {}, 'known_functions': {<class 'sympy.core.add.Add'>: '+', <class 'sympy.core.mul.Mul'>: '*', <class 'sympy.core.power.Pow'>: 'pow', <class 'sympy.core.relational.Equality'>: '=', <class 'sympy.core.relational.GreaterThan'>: '>=', <class 'sympy.core.relational.LessThan'>: '<=', <class 'sympy.core.relational.StrictGreaterThan'>: '>', <class 'sympy.core.relational.StrictLessThan'>: '<', Abs: 'abs', And: 'and', ITE: 'ite', Implies: '=>', Max: 'max', Min: 'min', Not: 'not', Or: 'or', Q.eq: '=', Q.ge: '>=', Q.gt: '>', Q.le: '<=', Q.lt: '<', Xor: 'xor', acos: 'arccos', asin: 'arcsin', atan: 'arctan', atan2: 'arctan2', cos: 'cos', cosh: 'cosh', exp: 'exp', log: 'log', sin: 'sin', sinh: 'sinh', tan: 'tan', tanh: 'tanh'}, 'known_types': {<class 'bool'>: 'Bool', <class 'float'>: 'Real', <class 'int'>: 'Int'}, 'precision': None}#
- sympy.printing.smtlib.smtlib_code(expr, auto_assert=True, auto_declare=True, precision=None, symbol_table=None, known_types=None, known_constants=None, known_functions=None, prefix_expressions=None, suffix_expressions=None, log_warn=None)[源代码]#
Converts
exprto a string of smtlib code.- 参数:
expr : Expr | List[Expr]
A SymPy expression or system to be converted.
auto_assert : bool, optional
If false, do not modify expr and produce only the S-Expression equivalent of expr. If true, assume expr is a system and assert each boolean element.
auto_declare : bool, optional
If false, do not produce declarations for the symbols used in expr. If true, prepend all necessary declarations for variables used in expr based on symbol_table.
精度 :整数,可选
The
evalf(..)precision for numbers such as pi.symbol_table : dict, optional
A dictionary where keys are
SymbolorFunctioninstances and values are their Python type i.e.bool,int,float, orCallable[...]. If incomplete, an attempt will be made to infer types fromexpr.known_types: dict, optional
A dictionary where keys are
bool,int,floatetc. and values are their corresponding SMT type names. If not given, a partial listing compatible with several solvers will be used.known_functions : dict, optional
A dictionary where keys are
Function,Relational,BooleanFunction, orExprinstances and values are their SMT string representations. If not given, a partial listing optimized for dReal solver (but compatible with others) will be used.known_constants: dict, optional
A dictionary where keys are
NumberSymbolinstances and values are their SMT variable names. When using this feature, extra caution must be taken to avoid naming collisions between user symbols and listed constants. If not given, constants will be expanded inline i.e.3.14159instead ofMY_SMT_VARIABLE_FOR_PI.prefix_expressions: list, optional
A list of lists of
strand/or expressions to convert into SMTLib and prefix to the output.suffix_expressions: list, optional
A list of lists of
strand/or expressions to convert into SMTLib and postfix to the output.log_warn: lambda function, optional
A function to record all warnings during potentially risky operations. Soundness is a core value in SMT solving, so it is good to log all assumptions made.
实例
>>> from sympy import smtlib_code, symbols, sin, Eq >>> x = symbols('x') >>> smtlib_code(sin(x).series(x).removeO(), log_warn=print) Could not infer type of `x`. Defaulting to float. Non-Boolean expression `x**5/120 - x**3/6 + x` will not be asserted. Converting to SMTLib verbatim. '(declare-const x Real)\n(+ x (* (/ -1 6) (pow x 3)) (* (/ 1 120) (pow x 5)))'
>>> from sympy import Rational >>> x, y, tau = symbols("x, y, tau") >>> smtlib_code((2*tau)**Rational(7, 2), log_warn=print) Could not infer type of `tau`. Defaulting to float. Non-Boolean expression `8*sqrt(2)*tau**(7/2)` will not be asserted. Converting to SMTLib verbatim. '(declare-const tau Real)\n(* 8 (pow 2 (/ 1 2)) (pow tau (/ 7 2)))'
Piecewiseexpressions are implemented withiteexpressions by default. Note that if thePiecewiselacks a default term, represented by(expr, True)then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything.>>> from sympy import Piecewise >>> pw = Piecewise((x + 1, x > 0), (x, True)) >>> smtlib_code(Eq(pw, 3), symbol_table={x: float}, log_warn=print) '(declare-const x Real)\n(assert (= (ite (> x 0) (+ 1 x) x) 3))'
Custom printing can be defined for certain types by passing a dictionary of PythonType : "SMT Name" to the
known_types,known_constants, andknown_functionskwargs.>>> from typing import Callable >>> from sympy import Function, Add >>> f = Function('f') >>> g = Function('g') >>> smt_builtin_funcs = { # functions our SMT solver will understand ... f: "existing_smtlib_fcn", ... Add: "sum", ... } >>> user_def_funcs = { # functions defined by the user must have their types specified explicitly ... g: Callable[[int], float], ... } >>> smtlib_code(f(x) + g(x), symbol_table=user_def_funcs, known_functions=smt_builtin_funcs, log_warn=print) Non-Boolean expression `f(x) + g(x)` will not be asserted. Converting to SMTLib verbatim. '(declare-const x Int)\n(declare-fun g (Int) Real)\n(sum (existing_smtlib_fcn x) (g x))'
Mathematica代码打印#
- sympy.printing.mathematica.known_functions = {'Chi': [(<function <lambda>>, 'CoshIntegral')], 'Ci': [(<function <lambda>>, 'CosIntegral')], 'DiracDelta': [(<function <lambda>>, 'DiracDelta')], 'Ei': [(<function <lambda>>, 'ExpIntegralEi')], 'FallingFactorial': [(<function <lambda>>, 'FactorialPower')], 'Heaviside': [(<function <lambda>>, 'HeavisideTheta')], 'KroneckerDelta': [(<function <lambda>>, 'KroneckerDelta')], 'Max': [(<function <lambda>>, 'Max')], 'Min': [(<function <lambda>>, 'Min')], 'RisingFactorial': [(<function <lambda>>, 'Pochhammer')], 'Shi': [(<function <lambda>>, 'SinhIntegral')], 'Si': [(<function <lambda>>, 'SinIntegral')], 'acos': [(<function <lambda>>, 'ArcCos')], 'acosh': [(<function <lambda>>, 'ArcCosh')], 'acot': [(<function <lambda>>, 'ArcCot')], 'acoth': [(<function <lambda>>, 'ArcCoth')], 'acsc': [(<function <lambda>>, 'ArcCsc')], 'acsch': [(<function <lambda>>, 'ArcCsch')], 'airyai': [(<function <lambda>>, 'AiryAi')], 'airyaiprime': [(<function <lambda>>, 'AiryAiPrime')], 'airybi': [(<function <lambda>>, 'AiryBi')], 'airybiprime': [(<function <lambda>>, 'AiryBiPrime')], 'appellf1': [(<function <lambda>>, 'AppellF1')], 'asec': [(<function <lambda>>, 'ArcSec')], 'asech': [(<function <lambda>>, 'ArcSech')], 'asin': [(<function <lambda>>, 'ArcSin')], 'asinh': [(<function <lambda>>, 'ArcSinh')], 'assoc_laguerre': [(<function <lambda>>, 'LaguerreL')], 'assoc_legendre': [(<function <lambda>>, 'LegendreP')], 'atan': [(<function <lambda>>, 'ArcTan')], 'atan2': [(<function <lambda>>, 'ArcTan')], 'atanh': [(<function <lambda>>, 'ArcTanh')], 'besseli': [(<function <lambda>>, 'BesselI')], 'besselj': [(<function <lambda>>, 'BesselJ')], 'besselk': [(<function <lambda>>, 'BesselK')], 'bessely': [(<function <lambda>>, 'BesselY')], 'beta': [(<function <lambda>>, 'Beta')], 'catalan': [(<function <lambda>>, 'CatalanNumber')], 'chebyshevt': [(<function <lambda>>, 'ChebyshevT')], 'chebyshevu': [(<function <lambda>>, 'ChebyshevU')], 'conjugate': [(<function <lambda>>, 'Conjugate')], 'cos': [(<function <lambda>>, 'Cos')], 'cosh': [(<function <lambda>>, 'Cosh')], 'cot': [(<function <lambda>>, 'Cot')], 'coth': [(<function <lambda>>, 'Coth')], 'csc': [(<function <lambda>>, 'Csc')], 'csch': [(<function <lambda>>, 'Csch')], 'dirichlet_eta': [(<function <lambda>>, 'DirichletEta')], 'elliptic_e': [(<function <lambda>>, 'EllipticE')], 'elliptic_f': [(<function <lambda>>, 'EllipticE')], 'elliptic_k': [(<function <lambda>>, 'EllipticK')], 'elliptic_pi': [(<function <lambda>>, 'EllipticPi')], 'erf': [(<function <lambda>>, 'Erf')], 'erf2': [(<function <lambda>>, 'Erf')], 'erf2inv': [(<function <lambda>>, 'InverseErf')], 'erfc': [(<function <lambda>>, 'Erfc')], 'erfcinv': [(<function <lambda>>, 'InverseErfc')], 'erfi': [(<function <lambda>>, 'Erfi')], 'erfinv': [(<function <lambda>>, 'InverseErf')], 'exp': [(<function <lambda>>, 'Exp')], 'expint': [(<function <lambda>>, 'ExpIntegralE')], 'factorial': [(<function <lambda>>, 'Factorial')], 'factorial2': [(<function <lambda>>, 'Factorial2')], 'fresnelc': [(<function <lambda>>, 'FresnelC')], 'fresnels': [(<function <lambda>>, 'FresnelS')], 'gamma': [(<function <lambda>>, 'Gamma')], 'gcd': [(<function <lambda>>, 'GCD')], 'gegenbauer': [(<function <lambda>>, 'GegenbauerC')], 'hankel1': [(<function <lambda>>, 'HankelH1')], 'hankel2': [(<function <lambda>>, 'HankelH2')], 'harmonic': [(<function <lambda>>, 'HarmonicNumber')], 'hermite': [(<function <lambda>>, 'HermiteH')], 'hyper': [(<function <lambda>>, 'HypergeometricPFQ')], 'jacobi': [(<function <lambda>>, 'JacobiP')], 'jn': [(<function <lambda>>, 'SphericalBesselJ')], 'laguerre': [(<function <lambda>>, 'LaguerreL')], 'lcm': [(<function <lambda>>, 'LCM')], 'legendre': [(<function <lambda>>, 'LegendreP')], 'lerchphi': [(<function <lambda>>, 'LerchPhi')], 'li': [(<function <lambda>>, 'LogIntegral')], 'log': [(<function <lambda>>, 'Log')], 'loggamma': [(<function <lambda>>, 'LogGamma')], 'lucas': [(<function <lambda>>, 'LucasL')], 'mathieuc': [(<function <lambda>>, 'MathieuC')], 'mathieucprime': [(<function <lambda>>, 'MathieuCPrime')], 'mathieus': [(<function <lambda>>, 'MathieuS')], 'mathieusprime': [(<function <lambda>>, 'MathieuSPrime')], 'meijerg': [(<function <lambda>>, 'MeijerG')], 'polygamma': [(<function <lambda>>, 'PolyGamma')], 'polylog': [(<function <lambda>>, 'PolyLog')], 'riemann_xi': [(<function <lambda>>, 'RiemannXi')], 'sec': [(<function <lambda>>, 'Sec')], 'sech': [(<function <lambda>>, 'Sech')], 'sin': [(<function <lambda>>, 'Sin')], 'sinc': [(<function <lambda>>, 'Sinc')], 'sinh': [(<function <lambda>>, 'Sinh')], 'sqrt': [(<function <lambda>>, 'Sqrt')], 'stieltjes': [(<function <lambda>>, 'StieltjesGamma')], 'subfactorial': [(<function <lambda>>, 'Subfactorial')], 'tan': [(<function <lambda>>, 'Tan')], 'tanh': [(<function <lambda>>, 'Tanh')], 'uppergamma': [(<function <lambda>>, 'Gamma')], 'yn': [(<function <lambda>>, 'SphericalBesselY')], 'zeta': [(<function <lambda>>, 'Zeta')]}#
枫码印刷#
- class sympy.printing.maple.MapleCodePrinter(settings=None)[源代码]#
Printer which converts a SymPy expression into a maple code.
- printmethod: str = '_maple'#
- sympy.printing.maple.maple_code(expr, assign_to=None, **settings)[源代码]#
皈依者
expr一系列的Maple代码。- 参数:
expr :表达式
A SymPy expression to be converted.
assign_to :可选
当给定参数时,参数将用作表达式分配给的变量的名称。可以是字符串,
Symbol,MatrixSymbol或Indexed类型。这对于生成多行语句的表达式非常有用。精度 :整数,可选
像pi这样的数字的精度 [default=16] .
user_functions :dict,可选
有钥匙的词典
FunctionClass实例和值是它们的字符串表示。或者,字典值可以是元组的列表,即。 [(argument_test, cfunction_string)] . 示例见下文。人类 :bool,可选
如果为True,则结果是一个字符串,它可能包含一些数字符号的常量声明。如果为False,则相同的信息将在元组中返回(符号_to_udeclare,not u supported_ufunctions,code_utext)。 [default=True] .
合同:bool,可选
如果属实,
Indexed假设实例服从张量收缩规则,并在索引上生成相应的嵌套循环。设置contract=False不会生成循环,相反,用户负责为代码中的索引提供值。 [default=True] .inline:bool,可选
如果为True,则尝试创建单语句代码,而不是多个语句。 [default=True] .
- sympy.printing.maple.print_maple_code(expr, **settings)[源代码]#
打印给定表达式的Maple表示形式。
见
maple_code()了解可选参数的含义。实例
>>> from sympy import print_maple_code, symbols >>> x, y = symbols('x y') >>> print_maple_code(x, assign_to=y) y := x
Javascript代码打印#
- sympy.printing.jscode.known_functions = {'Abs': 'Math.abs', 'Max': 'Math.max', 'Min': 'Math.min', 'acos': 'Math.acos', 'acosh': 'Math.acosh', 'asin': 'Math.asin', 'asinh': 'Math.asinh', 'atan': 'Math.atan', 'atan2': 'Math.atan2', 'atanh': 'Math.atanh', 'ceiling': 'Math.ceil', 'cos': 'Math.cos', 'cosh': 'Math.cosh', 'exp': 'Math.exp', 'floor': 'Math.floor', 'log': 'Math.log', 'sign': 'Math.sign', 'sin': 'Math.sin', 'sinh': 'Math.sinh', 'tan': 'Math.tan', 'tanh': 'Math.tanh'}#
- class sympy.printing.jscode.JavascriptCodePrinter(settings={})[源代码]#
"A Printer to convert Python expressions to strings of JavaScript code
- printmethod: str = '_javascript'#
- sympy.printing.jscode.jscode(expr, assign_to=None, **settings)[源代码]#
将expr转换为javascript代码字符串
- 参数:
expr :表达式
A SymPy expression to be converted.
assign_to :可选
当给定参数时,参数将用作表达式分配给的变量的名称。可以是字符串,
Symbol,MatrixSymbol或Indexed类型。这对于换行或生成多行语句的表达式非常有用。精度 :整数,可选
像pi这样的数字的精度 [default=15] .
user_functions :dict,可选
有钥匙的词典
FunctionClass实例和值是它们的字符串表示。或者,字典值可以是元组的列表,即。 [(argument_test, js_function_string)] . 示例见下文。人类 :bool,可选
如果为True,则结果为单个字符串,其中可能包含数字符号的某些常量声明。如果为False,则在元组中返回相同的信息(symbols_to_declare,不支持_functions,code_text)。 [default=True] .
合同:bool,可选
如果属实,
Indexed假设实例服从张量收缩规则,并在索引上生成相应的嵌套循环。设置contract=False不会生成循环,相反,用户负责为代码中的索引提供值。 [default=True] .
实例
>>> from sympy import jscode, symbols, Rational, sin, ceiling, Abs >>> x, tau = symbols("x, tau") >>> jscode((2*tau)**Rational(7, 2)) '8*Math.sqrt(2)*Math.pow(tau, 7/2)' >>> jscode(sin(x), assign_to="s") 's = Math.sin(x);'
通过将“type”:“function”字典传递给
user_functions夸克。或者,字典值可以是元组的列表,即。 [(argument_test, js_function_string)] .>>> custom_functions = { ... "ceiling": "CEIL", ... "Abs": [(lambda x: not x.is_integer, "fabs"), ... (lambda x: x.is_integer, "ABS")] ... } >>> jscode(Abs(x) + ceiling(x), user_functions=custom_functions) 'fabs(x) + CEIL(x)'
Piecewise表达式被转换成条件句。如果assign_to变量提供一个if语句,否则使用三元运算符。注意如果Piecewise缺少默认术语,表示为(expr, True)然后抛出一个错误。这是为了防止生成一个可能无法计算任何结果的表达式。>>> from sympy import Piecewise >>> expr = Piecewise((x + 1, x > 0), (x, True)) >>> print(jscode(expr, tau)) if (x > 0) { tau = x + 1; } else { tau = x; }
对循环的支持通过
Indexed类型。与contract=True这些表达式将变成循环,而contract=False将只打印应该循环的赋值表达式:>>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> jscode(e.rhs, assign_to=e.lhs, contract=False) 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
也支持矩阵,但是
MatrixSymbol必须提供相同尺寸的assign_to. 也可以在正常情况下生成的矩阵中存在:>>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) >>> A = MatrixSymbol('A', 3, 1) >>> print(jscode(mat, A)) A[0] = Math.pow(x, 2); if (x > 0) { A[1] = x + 1; } else { A[1] = x; } A[2] = Math.sin(x);
茱莉亚码印刷#
- sympy.printing.julia.known_fcns_src1 = ['sin', 'cos', 'tan', 'cot', 'sec', 'csc', 'asin', 'acos', 'atan', 'acot', 'asec', 'acsc', 'sinh', 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh', 'acoth', 'asech', 'acsch', 'sinc', 'atan2', 'sign', 'floor', 'log', 'exp', 'cbrt', 'sqrt', 'erf', 'erfc', 'erfi', 'factorial', 'gamma', 'digamma', 'trigamma', 'polygamma', 'beta', 'airyai', 'airyaiprime', 'airybi', 'airybiprime', 'besselj', 'bessely', 'besseli', 'besselk', 'erfinv', 'erfcinv']#
内置可变序列。
如果没有给定参数,则构造函数将创建一个新的空列表。如果指定,则参数必须是ITerable。
- sympy.printing.julia.known_fcns_src2 = {'Abs': 'abs', 'ceiling': 'ceil', 'conjugate': 'conj', 'hankel1': 'hankelh1', 'hankel2': 'hankelh2', 'im': 'imag', 're': 'real'}#
- class sympy.printing.julia.JuliaCodePrinter(settings={})[源代码]#
把表达式转换成Julia码字符串的打印机。
- printmethod: str = '_julia'#
- sympy.printing.julia.julia_code(expr, assign_to=None, **settings)[源代码]#
皈依者 \(expr\) 一系列的Julia密码。
- 参数:
expr :表达式
A SymPy expression to be converted.
assign_to :可选
当给定参数时,参数将用作表达式分配给的变量的名称。可以是字符串,
Symbol,MatrixSymbol或Indexed类型。这对于生成多行语句的表达式非常有用。精度 :整数,可选
像pi这样的数字的精度 [default=16] .
user_functions :dict,可选
有钥匙的词典
FunctionClass实例和值是它们的字符串表示。或者,字典值可以是元组的列表,即。 [(argument_test, cfunction_string)] . 示例见下文。人类 :bool,可选
如果为True,则结果是一个字符串,它可能包含一些数字符号的常量声明。如果为False,则相同的信息将在元组中返回(符号_to_udeclare,not u supported_ufunctions,code_utext)。 [default=True] .
合同:bool,可选
如果属实,
Indexed假设实例服从张量收缩规则,并在索引上生成相应的嵌套循环。设置contract=False不会生成循环,相反,用户负责为代码中的索引提供值。 [default=True] .inline:bool,可选
如果为True,则尝试创建单语句代码,而不是多个语句。 [default=True] .
实例
>>> from sympy import julia_code, symbols, sin, pi >>> x = symbols('x') >>> julia_code(sin(x).series(x).removeO()) 'x .^ 5 / 120 - x .^ 3 / 6 + x'
>>> from sympy import Rational, ceiling >>> x, y, tau = symbols("x, y, tau") >>> julia_code((2*tau)**Rational(7, 2)) '8 * sqrt(2) * tau .^ (7 // 2)'
注意,默认情况下在符号之间使用元素级(Hadamard)操作。这是因为Julia有可能编写“矢量化”代码。如果这些值是标量,则是无害的。
>>> julia_code(sin(pi*x*y), assign_to="s") 's = sin(pi * x .* y)'
如果需要矩阵乘积“*”或矩阵幂“^”,可以将符号指定为
MatrixSymbol.>>> from sympy import Symbol, MatrixSymbol >>> n = Symbol('n', integer=True, positive=True) >>> A = MatrixSymbol('A', n, n) >>> julia_code(3*pi*A**3) '(3 * pi) * A ^ 3'
此类使用多个规则来决定使用产品的符号。纯数字使用“ “使用符号”。 “和矩阵符号使用” ". HadamardProduct可用于指定组件式乘法”。 两个矩阵符号。目前还没有简单的方法来指定标量符号,因此有时代码可能会有一些小的修饰问题。例如,假设x和y是标量,A是矩阵,那么当一个程序员编写“(x^2 y) A^3“,我们生成:
>>> julia_code(x**2*y*A**3) '(x .^ 2 .* y) * A ^ 3'
使用Julia内联表示法支持矩阵。使用时
assign_to对于矩阵,名称可以指定为字符串或MatrixSymbol. 在后一种情况下,尺寸必须对齐。>>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([[x**2, sin(x), ceiling(x)]]) >>> julia_code(mat, assign_to='A') 'A = [x .^ 2 sin(x) ceil(x)]'
Piecewise默认情况下,表达式是用逻辑屏蔽实现的。或者,可以传递“inline=False”以使用if-else条件。注意如果Piecewise缺少默认术语,表示为(expr, True)然后抛出一个错误。这是为了防止生成一个可能无法计算任何结果的表达式。>>> from sympy import Piecewise >>> pw = Piecewise((x + 1, x > 0), (x, True)) >>> julia_code(pw, assign_to=tau) 'tau = ((x > 0) ? (x + 1) : (x))'
也可以在正常情况下生成的矩阵中存在:
>>> mat = Matrix([[x**2, pw, sin(x)]]) >>> julia_code(mat, assign_to='A') 'A = [x .^ 2 ((x > 0) ? (x + 1) : (x)) sin(x)]'
通过将“type”:“function”字典传递给
user_functions夸克。或者,字典值可以是元组的列表,即。, [(argument_test, cfunction_string)] . 这可用于调用自定义Julia函数。>>> from sympy import Function >>> f = Function('f') >>> g = Function('g') >>> custom_functions = { ... "f": "existing_julia_fcn", ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"), ... (lambda x: not x.is_Matrix, "my_fcn")] ... } >>> mat = Matrix([[1, x]]) >>> julia_code(f(x) + g(x) + g(mat), user_functions=custom_functions) 'existing_julia_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])'
对循环的支持通过
Indexed类型。与contract=True这些表达式将变成循环,而contract=False将只打印应该循环的赋值表达式:>>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> julia_code(e.rhs, assign_to=e.lhs, contract=False) 'Dy[i] = (y[i + 1] - y[i]) ./ (t[i + 1] - t[i])'
倍频程(和Matlab)代码打印#
- sympy.printing.octave.known_fcns_src1 = ['sin', 'cos', 'tan', 'cot', 'sec', 'csc', 'asin', 'acos', 'acot', 'atan', 'atan2', 'asec', 'acsc', 'sinh', 'cosh', 'tanh', 'coth', 'csch', 'sech', 'asinh', 'acosh', 'atanh', 'acoth', 'asech', 'acsch', 'erfc', 'erfi', 'erf', 'erfinv', 'erfcinv', 'besseli', 'besselj', 'besselk', 'bessely', 'bernoulli', 'beta', 'euler', 'exp', 'factorial', 'floor', 'fresnelc', 'fresnels', 'gamma', 'harmonic', 'log', 'polylog', 'sign', 'zeta', 'legendre']#
内置可变序列。
如果没有给定参数,则构造函数将创建一个新的空列表。如果指定,则参数必须是ITerable。
- sympy.printing.octave.known_fcns_src2 = {'Abs': 'abs', 'Chi': 'coshint', 'Ci': 'cosint', 'DiracDelta': 'dirac', 'Heaviside': 'heaviside', 'LambertW': 'lambertw', 'Max': 'max', 'Min': 'min', 'Mod': 'mod', 'RisingFactorial': 'pochhammer', 'Shi': 'sinhint', 'Si': 'sinint', 'arg': 'angle', 'binomial': 'bincoeff', 'ceiling': 'ceil', 'chebyshevt': 'chebyshevT', 'chebyshevu': 'chebyshevU', 'conjugate': 'conj', 'im': 'imag', 'laguerre': 'laguerreL', 'li': 'logint', 'loggamma': 'gammaln', 'polygamma': 'psi', 're': 'real'}#
- class sympy.printing.octave.OctaveCodePrinter(settings={})[源代码]#
一种打印机,用于将表达式转换为倍频程/Matlab代码的字符串。
- printmethod: str = '_octave'#
- sympy.printing.octave.octave_code(expr, assign_to=None, **settings)[源代码]#
皈依者 \(expr\) 一系列倍频程(或Matlab)代码。
该字符串使用倍频程语言的一个子集,以与Matlab兼容。
- 参数:
expr :表达式
A SymPy expression to be converted.
assign_to :可选
当给定参数时,参数将用作表达式分配给的变量的名称。可以是字符串,
Symbol,MatrixSymbol或Indexed类型。这对于生成多行语句的表达式非常有用。精度 :整数,可选
像pi这样的数字的精度 [default=16] .
user_functions :dict,可选
有钥匙的词典
FunctionClass实例和值是它们的字符串表示。或者,字典值可以是元组的列表,即。 [(argument_test, cfunction_string)] . 示例见下文。人类 :bool,可选
如果为True,则结果是一个字符串,它可能包含一些数字符号的常量声明。如果为False,则相同的信息将在元组中返回(符号_to_udeclare,not u supported_ufunctions,code_utext)。 [default=True] .
合同:bool,可选
如果属实,
Indexed假设实例服从张量收缩规则,并在索引上生成相应的嵌套循环。设置contract=False不会生成循环,相反,用户负责为代码中的索引提供值。 [default=True] .inline:bool,可选
如果为True,则尝试创建单语句代码,而不是多个语句。 [default=True] .
实例
>>> from sympy import octave_code, symbols, sin, pi >>> x = symbols('x') >>> octave_code(sin(x).series(x).removeO()) 'x.^5/120 - x.^3/6 + x'
>>> from sympy import Rational, ceiling >>> x, y, tau = symbols("x, y, tau") >>> octave_code((2*tau)**Rational(7, 2)) '8*sqrt(2)*tau.^(7/2)'
注意,默认情况下在符号之间使用元素级(Hadamard)操作。这是因为在倍频程中编写“矢量化”代码非常常见。如果这些值是标量,则是无害的。
>>> octave_code(sin(pi*x*y), assign_to="s") 's = sin(pi*x.*y);'
如果需要矩阵乘积“*”或矩阵幂“^”,可以将符号指定为
MatrixSymbol.>>> from sympy import Symbol, MatrixSymbol >>> n = Symbol('n', integer=True, positive=True) >>> A = MatrixSymbol('A', n, n) >>> octave_code(3*pi*A**3) '(3*pi)*A^3'
此类使用多个规则来决定使用产品的符号。纯数字使用“ “使用符号”。 “和矩阵符号使用” ". HadamardProduct可用于指定组件式乘法”。 两个矩阵符号。目前还没有简单的方法来指定标量符号,因此有时代码可能会有一些小的修饰问题。例如,假设x和y是标量,A是矩阵,那么当一个程序员编写“(x^2 y) A^3“,我们生成:
>>> octave_code(x**2*y*A**3) '(x.^2.*y)*A^3'
使用倍频程内联表示法支持矩阵。使用时
assign_to对于矩阵,名称可以指定为字符串或MatrixSymbol. 在后一种情况下,尺寸必须对齐。>>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([[x**2, sin(x), ceiling(x)]]) >>> octave_code(mat, assign_to='A') 'A = [x.^2 sin(x) ceil(x)];'
Piecewise默认情况下,表达式是用逻辑屏蔽实现的。或者,可以传递“inline=False”以使用if-else条件。注意如果Piecewise缺少默认术语,表示为(expr, True)然后抛出一个错误。这是为了防止生成一个可能无法计算任何结果的表达式。>>> from sympy import Piecewise >>> pw = Piecewise((x + 1, x > 0), (x, True)) >>> octave_code(pw, assign_to=tau) 'tau = ((x > 0).*(x + 1) + (~(x > 0)).*(x));'
也可以在正常情况下生成的矩阵中存在:
>>> mat = Matrix([[x**2, pw, sin(x)]]) >>> octave_code(mat, assign_to='A') 'A = [x.^2 ((x > 0).*(x + 1) + (~(x > 0)).*(x)) sin(x)];'
通过将“type”:“function”字典传递给
user_functions夸克。或者,字典值可以是元组的列表,即。, [(argument_test, cfunction_string)] . 这可用于调用自定义倍频程函数。>>> from sympy import Function >>> f = Function('f') >>> g = Function('g') >>> custom_functions = { ... "f": "existing_octave_fcn", ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"), ... (lambda x: not x.is_Matrix, "my_fcn")] ... } >>> mat = Matrix([[1, x]]) >>> octave_code(f(x) + g(x) + g(mat), user_functions=custom_functions) 'existing_octave_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])'
对循环的支持通过
Indexed类型。与contract=True这些表达式将变成循环,而contract=False将只打印应该循环的赋值表达式:>>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> octave_code(e.rhs, assign_to=e.lhs, contract=False) 'Dy(i) = (y(i + 1) - y(i))./(t(i + 1) - t(i));'
锈码印刷#
- sympy.printing.rust.known_functions = {'Abs': 'abs', 'Max': 'max', 'Min': 'min', 'Pow': [(<function <lambda>>, 'recip', 2), (<function <lambda>>, 'sqrt', 2), (<function <lambda>>, 'sqrt().recip', 2), (<function <lambda>>, 'cbrt', 2), (<function <lambda>>, 'exp2', 3), (<function <lambda>>, 'powi', 1), (<function <lambda>>, 'powf', 1)], 'acos': 'acos', 'acosh': 'acosh', 'asin': 'asin', 'asinh': 'asinh', 'atan': 'atan', 'atan2': 'atan2', 'atanh': 'atanh', 'ceiling': 'ceil', 'cos': 'cos', 'cosh': 'cosh', 'exp': [(<function <lambda>>, 'exp', 2)], 'floor': 'floor', 'log': 'ln', 'sign': 'signum', 'sin': 'sin', 'sinh': 'sinh', 'sqrt': 'sqrt', 'tan': 'tan', 'tanh': 'tanh'}#
- class sympy.printing.rust.RustCodePrinter(settings={})[源代码]#
A printer to convert SymPy expressions to strings of Rust code
- printmethod: str = '_rust_code'#
- sympy.printing.rust.rust_code(expr, assign_to=None, **settings)[源代码]#
将表达式转换为Rust代码字符串
- 参数:
expr :表达式
A SymPy expression to be converted.
assign_to :可选
当给定参数时,参数将用作表达式分配给的变量的名称。可以是字符串,
Symbol,MatrixSymbol或Indexed类型。这对于换行或生成多行语句的表达式非常有用。精度 :整数,可选
像pi这样的数字的精度 [default=15] .
user_functions :dict,可选
一种字典,其中的键是
FunctionClass或UndefinedFunction实例和值是它们所需的C字符串表示形式。或者,字典值可以是元组的列表,即。 [(argument_test, cfunction_string)] . 示例见下文。撤销引用 :iterable,可选
在打印的代码表达式中应该被取消引用的一种符号。这些值将通过地址传递给函数。例如,如果
dereference=[a],生成的代码将打印出来(*a)而不是a.人类 :bool,可选
如果为True,则结果为单个字符串,其中可能包含数字符号的某些常量声明。如果为False,则在元组中返回相同的信息(symbols_to_declare,不支持_functions,code_text)。 [default=True] .
合同:bool,可选
如果属实,
Indexed假设实例服从张量收缩规则,并在索引上生成相应的嵌套循环。设置contract=False不会生成循环,相反,用户负责为代码中的索引提供值。 [default=True] .
实例
>>> from sympy import rust_code, symbols, Rational, sin, ceiling, Abs, Function >>> x, tau = symbols("x, tau") >>> rust_code((2*tau)**Rational(7, 2)) '8*1.4142135623731*tau.powf(7_f64/2.0)' >>> rust_code(sin(x), assign_to="s") 's = x.sin();'
Simple custom printing can be defined for certain types by passing a dictionary of {"type" : "function"} to the
user_functionskwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)].>>> custom_functions = { ... "ceiling": "CEIL", ... "Abs": [(lambda x: not x.is_integer, "fabs", 4), ... (lambda x: x.is_integer, "ABS", 4)], ... "func": "f" ... } >>> func = Function('func') >>> rust_code(func(Abs(x) + ceiling(x)), user_functions=custom_functions) '(fabs(x) + x.CEIL()).f()'
Piecewise表达式被转换成条件句。如果assign_to变量提供一个if语句,否则使用三元运算符。注意如果Piecewise缺少默认术语,表示为(expr, True)然后抛出一个错误。这是为了防止生成一个可能无法计算任何结果的表达式。>>> from sympy import Piecewise >>> expr = Piecewise((x + 1, x > 0), (x, True)) >>> print(rust_code(expr, tau)) tau = if (x > 0) { x + 1 } else { x };
对循环的支持通过
Indexed类型。与contract=True这些表达式将变成循环,而contract=False将只打印应该循环的赋值表达式:>>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> rust_code(e.rhs, assign_to=e.lhs, contract=False) 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
也支持矩阵,但是
MatrixSymbol必须提供相同尺寸的assign_to. 也可以在正常情况下生成的矩阵中存在:>>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) >>> A = MatrixSymbol('A', 3, 1) >>> print(rust_code(mat, A)) A = [x.powi(2), if (x > 0) { x + 1 } else { x }, x.sin()];
Aesara Code printing#
- class sympy.printing.aesaracode.AesaraPrinter(*args, **kwargs)[源代码]#
Code printer which creates Aesara symbolic expression graphs.
- 参数:
隐藏物 :dict命令
Cache dictionary to use. If None (default) will use the global cache. To create a printer which does not depend on or alter global state pass an empty dictionary. Note: the dictionary is not copied on initialization of the printer and will be updated in-place, so using the same dict object when creating multiple printers or making multiple calls to
aesara_code()oraesara_function()means the cache is shared between all these applications.
属性
隐藏物
(dict) A cache of Aesara variables which have been created for SymPy symbol-like objects (e.g.
sympy.core.symbol.Symbolorsympy.matrices.expressions.MatrixSymbol). This is used to ensure that all references to a given symbol in an expression (or multiple expressions) are printed as the same Aesara variable, which is created only once. Symbols are differentiated only by name and type. The format of the cache's contents should be considered opaque to the user.- printmethod: str = '_aesara'#
- doprint(expr, dtypes=None, broadcastables=None)[源代码]#
Convert a SymPy expression to a Aesara graph variable.
The
dtypesandbroadcastablesarguments are used to specify the data type, dimension, and broadcasting behavior of the Aesara variables corresponding to the free symbols inexpr. Each is a mapping from SymPy symbols to the value of the corresponding argument toaesara.tensor.var.TensorVariable.See the corresponding documentation page for more information on broadcasting in Aesara.
- 参数:
expr : sympy.core.expr.Expr.表达式
要打印的SymPy表达式。
D型 :dict命令
Mapping from SymPy symbols to Aesara datatypes to use when creating new Aesara variables for those symbols. Corresponds to the
dtypeargument toaesara.tensor.var.TensorVariable. Defaults to'floatX'for symbols not included in the mapping.可广播的 :dict命令
Mapping from SymPy symbols to the value of the
broadcastableargument toaesara.tensor.var.TensorVariableto use when creating Aesara variables for those symbols. Defaults to the empty tuple for symbols not included in the mapping (resulting in a scalar).- 返回:
aesara.graph.basic.Variable
A variable corresponding to the expression's value in a Aesara symbolic expression graph.
- sympy.printing.aesaracode.aesara_code(expr, cache=None, **kwargs)[源代码]#
Convert a SymPy expression into a Aesara graph variable.
- 参数:
expr : sympy.core.expr.Expr.表达式
SymPy expression object to convert.
隐藏物 :dict命令
Cached Aesara variables (see
AesaraPrinter.cache). Defaults to the module-level global cache.D型 :dict命令
Passed to
AesaraPrinter.doprint().可广播的 :dict命令
Passed to
AesaraPrinter.doprint().- 返回:
aesara.graph.basic.Variable
A variable corresponding to the expression's value in a Aesara symbolic expression graph.
- sympy.printing.aesaracode.aesara_function(inputs, outputs, scalar=False, *, dim=None, dims=None, broadcastables=None, **kwargs)[源代码]#
Create a Aesara function from SymPy expressions.
The inputs and outputs are converted to Aesara variables using
aesara_code()and then passed toaesara.function.- 参数:
inputs
构成函数输入的符号序列。
outputs
构成函数输出的表达式序列。每个表达式的自由符号必须是
inputs.标量 布尔
Convert 0-dimensional arrays in output to scalars. This will return a Python wrapper function around the Aesara function object.
隐藏物 :dict命令
Cached Aesara variables (see
AesaraPrinter.cache). Defaults to the module-level global cache.D型 :dict命令
Passed to
AesaraPrinter.doprint().可广播的 :dict命令
Passed to
AesaraPrinter.doprint().dims :dict命令
替代
broadcastables争论。从元素映射inputs表示关联数组/张量维数的整数。覆盖broadcastables如果给的话。dim :内景
Another alternative to the
broadcastablesargument. Common number of dimensions to use for all arrays/tensors.aesara_function([x, y], [...], dim=2)is equivalent to usingbroadcastables={x: (False, False), y: (False, False)}.- 返回:
可赎回的
A callable object which takes values of
inputsas positional arguments and returns an output array for each of the expressions inoutputs. Ifoutputsis a single expression the function will return a Numpy array, if it is a list of multiple expressions the function will return a list of arrays. See description of thesqueezeargument above for the behavior when a single output is passed in a list. The returned object will either be an instance ofaesara.compile.function.types.Functionor a Python wrapper function around one. In both cases, the returned value will have aaesara_functionattribute which points to the return value ofaesara.function.
实例
>>> from sympy.abc import x, y, z >>> from sympy.printing.aesaracode import aesara_function
一个有一个输入和一个输出的简单函数:
>>> f1 = aesara_function([x], [x**2 - 1], scalar=True) >>> f1(3) 8.0
具有多个输入和一个输出的函数:
>>> f2 = aesara_function([x, y, z], [(x**z + y**z)**(1/z)], scalar=True) >>> f2(3, 4, 2) 5.0
具有多个输入和多个输出的函数:
>>> f3 = aesara_function([x, y], [x**2 + y**2, x**2 - y**2], scalar=True) >>> f3(2, 3) [13.0, -5.0]
参见
- sympy.printing.aesaracode.dim_handling(inputs, dim=None, dims=None, broadcastables=None)[源代码]#
Get value of
broadcastablesargument toaesara_code()from keyword arguments toaesara_function().包括向后兼容性。
- 参数:
inputs
输入符号序列。
dim :内景
所有输入的公共尺寸。如果给定,则重写其他参数。
dims :dict命令
从输入符号到尺寸的映射。覆盖
broadcastables如果给的话。可广播的 :dict命令
Explicit value of
broadcastablesargument toAesaraPrinter.doprint(). If not None function will return this value unchanged.- 返回:
双关语
字典映射元素
inputs它们的“可广播”值(的元组bools)段。
Gtk公司#
您可以使用函数打印到gtkmathview小部件 print_gtk 位于 sympy.printing.gtk (某些系统需要安装gtkmathview和libgtkmathview bin)。
GtkMathView接受MathML,因此这种呈现依赖于表达式的MathML表示。
用法:
from sympy import *
print_gtk(x**2 + 2*exp(x**3))
LambdaPrinter#
这些类实现打印到可由 sympy.utilities.lambdify.lambdify() 功能。
LatexPrinter#
这个类实现 Latex 印刷。看到了吗 sympy.printing.latex .
- sympy.printing.latex.accepted_latex_functions = ['arcsin', 'arccos', 'arctan', 'sin', 'cos', 'tan', 'sinh', 'cosh', 'tanh', 'sqrt', 'ln', 'log', 'sec', 'csc', 'cot', 'coth', 're', 'im', 'frac', 'root', 'arg']#
内置可变序列。
如果没有给定参数,则构造函数将创建一个新的空列表。如果指定,则参数必须是ITerable。
- sympy.printing.latex.latex(expr, *, full_prec=False, fold_frac_powers=False, fold_func_brackets=False, fold_short_frac=None, inv_trig_style='abbreviated', itex=False, ln_notation=False, long_frac_ratio=None, mat_delim='[', mat_str=None, mode='plain', mul_symbol=None, order=None, symbol_names={}, root_notation=True, mat_symbol_style='plain', imaginary_unit='i', gothic_re_im=False, decimal_separator='period', perm_cyclic=True, parenthesize_super=True, min=None, max=None, diff_operator='d', adjoint_style='dagger')#
将给定的表达式转换为LaTeX字符串表示形式。
- 参数:
full_prec: boolean, optional
如果设置为True,则以全精度打印浮点数。
fold_frac_powers :布尔值,可选
发出
^{{p/q}}而不是^{{\frac{{p}}{{q}}}}分数次幂。fold_func_brackets :布尔值,可选
折叠功能支架(如适用)。
fold_short_frac :布尔值,可选
发出
p / q而不是\frac{{p}}{{q}}当分母足够简单时(最多两个术语,没有幂)。默认值为True对于内联模式,False否则。inv_trig_style :字符串,可选
How inverse trig functions should be displayed. Can be one of
'abbreviated','full', or'power'. Defaults to'abbreviated'.itex :布尔值,可选
指定是否使用itex特定的语法,包括发出
$$...$$.ln_notation :布尔值,可选
如果设置为
True,\ln使用而不是默认值\log.long_frac_ratio :浮动或无,可选
在打印机中断长分数之前,允许的分子宽度与分母宽度之比。如果
None(默认值),长分数不会被拆分。mat_delim :字符串,可选
The delimiter to wrap around matrices. Can be one of
'[','(', or the empty string''. Defaults to'['.mat_str :字符串,可选
Which matrix environment string to emit.
'smallmatrix','matrix','array', etc. Defaults to'smallmatrix'for inline mode,'matrix'for matrices of no more than 10 columns, and'array'otherwise.模式:字符串,可选
Specifies how the generated code will be delimited.
modecan be one of'plain','inline','equation'or'equation*'. Ifmodeis set to'plain', then the resulting code will not be delimited at all (this is the default). Ifmodeis set to'inline'then inline LaTeX$...$will be used. Ifmodeis set to'equation'or'equation*', the resulting code will be enclosed in theequationorequation*environment (remember to importamsmathforequation*), unless theitexoption is set. In the latter case, the$$...$$syntax is used.mul_symbol :字符串或无,可选
The symbol to use for multiplication. Can be one of
None,'ldot','dot', or'times'.顺序:字符串,可选
Any of the supported monomial orderings (currently
'lex','grlex', or'grevlex'),'old', and'none'. This parameter does nothing for \(~.Mul\) objects. Setting order to'old'uses the compatibility ordering for~.Adddefined in Printer. For very large expressions, set theorderkeyword to'none'if speed is a concern.symbol_names :映射到符号的字符串字典,可选
符号字典和它们应该作为其发出的自定义字符串。
root_notation :布尔值,可选
如果设置为
False,1/n形式的指数以分形形式打印。默认为True,以根形式打印指数。mat_symbol_style :字符串,可选
Can be either
'plain'(default) or'bold'. If set to'bold', a \(~.MatrixSymbol\) A will be printed as\mathbf{A}, otherwise asA.imaginary_unit :字符串,可选
String to use for the imaginary unit. Defined options are
'i'(default) and'j'. Addingrortin front gives\mathrmor\text, so'ri'leads to\mathrm{i}which gives \(\mathrm{i}\).gothic_re_im :布尔值,可选
如果设置为
True, \(\Re\) 和 \(\Im\) 用于re和im分别是。默认值是False导致 \(\operatorname{{re}}\) 和 \(\operatorname{{im}}\) .decimal_separator :字符串,可选
指定用于分隔浮点数的整个部分和小数部分的分隔符,如中所示 \(2.5\) 对于违约,
period或 \(2{{,}}5\) 什么时候?comma已指定。当comma是被选中的。例如, [1、 2;3] 什么时候?comma被选中并且 [1,2,3] 因为什么时候period是被选中的。parenthesize_super :布尔值,可选
如果设置为
False,通电时,上标表达式将不带圆括号。默认为True,它在通电时将表达式括起来。min:整数或无,可选
设置以定点格式打印浮点数的指数下限。
max:整数或无,可选
设置以定点格式打印浮点数的指数的上限。
diff_operator: string, optional
String to use for differential operator. Default is
'd', to print in italic form.'rd','td'are shortcuts for\mathrm{d}and\text{d}.adjoint_style: string, optional
String to use for the adjoint symbol. Defined options are
'dagger'(default),``'star', and ``'hermitian'.
笔记
因为在Python的反斜杠打印命令中,反斜杠的打印方式不使用反斜杠。
>>> from sympy import latex, Rational >>> from sympy.abc import tau >>> latex((2*tau)**Rational(7,2)) '8 \\sqrt{2} \\tau^{\\frac{7}{2}}' >>> print(latex((2*tau)**Rational(7,2))) 8 \sqrt{2} \tau^{\frac{7}{2}}
实例
>>> from sympy import latex, pi, sin, asin, Integral, Matrix, Rational, log >>> from sympy.abc import x, y, mu, r, tau
基本用法:
>>> print(latex((2*tau)**Rational(7,2))) 8 \sqrt{2} \tau^{\frac{7}{2}}
mode和itex选项:>>> print(latex((2*mu)**Rational(7,2), mode='plain')) 8 \sqrt{2} \mu^{\frac{7}{2}} >>> print(latex((2*tau)**Rational(7,2), mode='inline')) $8 \sqrt{2} \tau^{7 / 2}$ >>> print(latex((2*mu)**Rational(7,2), mode='equation*')) \begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*} >>> print(latex((2*mu)**Rational(7,2), mode='equation')) \begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation} >>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True)) $$8 \sqrt{2} \mu^{\frac{7}{2}}$$ >>> print(latex((2*mu)**Rational(7,2), mode='plain')) 8 \sqrt{2} \mu^{\frac{7}{2}} >>> print(latex((2*tau)**Rational(7,2), mode='inline')) $8 \sqrt{2} \tau^{7 / 2}$ >>> print(latex((2*mu)**Rational(7,2), mode='equation*')) \begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*} >>> print(latex((2*mu)**Rational(7,2), mode='equation')) \begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation} >>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True)) $$8 \sqrt{2} \mu^{\frac{7}{2}}$$
分数选项:
>>> print(latex((2*tau)**Rational(7,2), fold_frac_powers=True)) 8 \sqrt{2} \tau^{7/2} >>> print(latex((2*tau)**sin(Rational(7,2)))) \left(2 \tau\right)^{\sin{\left(\frac{7}{2} \right)}} >>> print(latex((2*tau)**sin(Rational(7,2)), fold_func_brackets=True)) \left(2 \tau\right)^{\sin {\frac{7}{2}}} >>> print(latex(3*x**2/y)) \frac{3 x^{2}}{y} >>> print(latex(3*x**2/y, fold_short_frac=True)) 3 x^{2} / y >>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=2)) \frac{\int r\, dr}{2 \pi} >>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=0)) \frac{1}{2 \pi} \int r\, dr
乘法选项:
>>> print(latex((2*tau)**sin(Rational(7,2)), mul_symbol="times")) \left(2 \times \tau\right)^{\sin{\left(\frac{7}{2} \right)}}
触发选项:
>>> print(latex(asin(Rational(7,2)))) \operatorname{asin}{\left(\frac{7}{2} \right)} >>> print(latex(asin(Rational(7,2)), inv_trig_style="full")) \arcsin{\left(\frac{7}{2} \right)} >>> print(latex(asin(Rational(7,2)), inv_trig_style="power")) \sin^{-1}{\left(\frac{7}{2} \right)}
矩阵选项:
>>> print(latex(Matrix(2, 1, [x, y]))) \left[\begin{matrix}x\\y\end{matrix}\right] >>> print(latex(Matrix(2, 1, [x, y]), mat_str = "array")) \left[\begin{array}{c}x\\y\end{array}\right] >>> print(latex(Matrix(2, 1, [x, y]), mat_delim="(")) \left(\begin{matrix}x\\y\end{matrix}\right)
自定义符号打印:
>>> print(latex(x**2, symbol_names={x: 'x_i'})) x_i^{2}
对数:
>>> print(latex(log(10))) \log{\left(10 \right)} >>> print(latex(log(10), ln_notation=True)) \ln{\left(10 \right)}
latex()还支持内置容器类型list,tuple和dict:>>> print(latex([2/x, y], mode='inline')) $\left[ 2 / x, \ y\right]$
不支持的类型呈现为等距纯文本:
>>> print(latex(int)) \mathtt{\text{<class 'int'>}} >>> print(latex("plain % text")) \mathtt{\text{plain \% text}}
见 自定义打印方法示例 例如,如何通过实现
_latex.在 1.7.0 版本发生变更: 不受支持的类型不再具有
str代表性视为有效 Latex 。
MathMLPrinter#
这个类负责MathML打印。看到了吗 sympy.printing.mathml .
More info on mathml : https://www.w3.org/TR/MathML2
- class sympy.printing.mathml.MathMLPrinterBase(settings=None)[源代码]#
包含MathMLContentPrinter和MathMLPresentationPrinter所需的通用代码。
- class sympy.printing.mathml.MathMLContentPrinter(settings=None)[源代码]#
将表达式打印到内容MathML标记语言。
参考文献:https://www.w3.org/TR/MathML2/chapter4.html
- printmethod: str = '_mathml_content'#
- class sympy.printing.mathml.MathMLPresentationPrinter(settings=None)[源代码]#
将表达式打印到Presentation MathML标记语言。
参考文献:https://www.w3.org/TR/MathML2/chapter3.html
- printmethod: str = '_mathml_presentation'#
- sympy.printing.mathml.mathml(expr, printer='content', *, order=None, encoding='utf-8', fold_frac_powers=False, fold_func_brackets=False, fold_short_frac=None, inv_trig_style='abbreviated', ln_notation=False, long_frac_ratio=None, mat_delim='[', mat_symbol_style='plain', mul_symbol=None, root_notation=True, symbol_names={}, mul_symbol_mathml_numbers='·')#
返回expr的MathML表示形式。如果打印机是presentation,则打印presentation MathML,否则打印content MathML。
- sympy.printing.mathml.print_mathml(expr, printer='content', **settings)[源代码]#
为expr打印一个漂亮的MathML代码表示。如果打印机是presentation,则打印presentation MathML,否则打印content MathML。
实例
>>> ## >>> from sympy import print_mathml >>> from sympy.abc import x >>> print_mathml(x+1) <apply> <plus/> <ci>x</ci> <cn>1</cn> </apply> >>> print_mathml(x+1, printer='presentation') <mrow> <mi>x</mi> <mo>+</mo> <mn>1</mn> </mrow>
PythonCodePrinter#
Python代码打印机
This module contains Python code printers for plain Python as well as NumPy & SciPy enabled code.
- sympy.printing.pycode.pycode(expr, **settings)[源代码]#
将一个字符串转换为一个表达式
- 参数:
expr :表达式
同情的表情。
fully_qualified_modules 布尔
是否写出函数的完整模块名 (
math.sinVSsin). 违约:True.标准 :str或None,可选
Only 'python3' (default) is supported. This parameter may be removed in the future.
实例
>>> from sympy import pycode, tan, Symbol >>> pycode(tan(Symbol('x')) + 1) 'math.tan(x) + 1'
PythonPrinter#
这个类实现Python打印。用法:
>>> from sympy import print_python, sin
>>> from sympy.abc import x
>>> print_python(5*x**3 + sin(x))
x = Symbol('x')
e = 5*x**3 + sin(x)
srepr公司#
打印机生成此可执行代码。此代码满足标识 eval(srepr(expr)) == expr .
srepr() gives more low level textual output than repr()
例子::
>>> repr(5*x**3 + sin(x))
'5*x**3 + sin(x)'
>>> srepr(5*x**3 + sin(x))
"Add(Mul(Integer(5), Pow(Symbol('x'), Integer(3))), sin(Symbol('x')))"
srepr() gives the repr form, which is what repr() would normally give
but for SymPy we don’t actually use srepr() for __repr__ because it’s
is so verbose, it is unlikely that anyone would want it called by default.
Another reason is that lists call repr on their elements, like print([a, b, c])
calls repr(a), repr(b), repr(c). So if we used srepr for __repr__ any list with
SymPy objects would include the srepr form, even if we used str() or print().
- sympy.printing.repr.srepr(expr, *, order=None, perm_cyclic=True)#
以repr形式返回表达式
StrPrinter#
此模块生成SymPy表达式的可读表示。
- sympy.printing.str.sstr(expr, *, order=None, full_prec='auto', sympy_integers=False, abbrev=False, perm_cyclic=True, min=None, max=None)#
以字符串形式返回表达式。
对于需要考虑速度的大型表达式,请使用设置顺序=“无”。如果使用abbrev=True设置,则单位以缩写形式打印。
实例
>>> from sympy import symbols, Eq, sstr >>> a, b = symbols('a b') >>> sstr(Eq(a + b, 0)) 'Eq(a + b, 0)'
- sympy.printing.str.sstrrepr(expr, *, order=None, full_prec='auto', sympy_integers=False, abbrev=False, perm_cyclic=True, min=None, max=None)#
以混合str/repr格式返回表达式
i、 字符串以带有引号的repr形式返回,其他的都以str形式返回。
此函数对于挂接到系统显示挂钩
树形打印#
此模块中的函数将表达式创建为树的表示形式。
- sympy.printing.tree.pprint_nodes(subtrees)[源代码]#
预打印节点系统。
实例
>>> from sympy.printing.tree import pprint_nodes >>> print(pprint_nodes(["a", "b1\nb2", "c"])) +-a +-b1 | b2 +-c
- sympy.printing.tree.print_node(node, assumptions=True)[源代码]#
返回有关“节点”的信息。
这包括类名、字符串表示和假设。
- 参数:
假设 :bool,可选
见
assumptions关键字在tree
- sympy.printing.tree.tree(node, assumptions=True)[源代码]#
以字符串形式返回“node”的树表示形式。
它在上使用print_node()和pprint_nodes()节点.args递归地。
- 参数:
假设 :bool,可选
例如决定是否打印所有数据 ``is_integer`, `` 是否与表达式关联。
启用标志会使结果变得冗长,并且打印的结果可能不是确定的,因为在回溯假设时使用了随机性。
参见
- sympy.printing.tree.print_tree(node, assumptions=True)[源代码]#
打印“node”的树表示。
- 参数:
假设 :bool,可选
例如决定是否打印所有数据 ``is_integer`, `` 是否与表达式关联。
启用标志会使结果变得冗长,并且打印的结果可能不是确定的,因为在回溯假设时使用了随机性。
实例
>>> from sympy.printing import print_tree >>> from sympy import Symbol >>> x = Symbol('x', odd=True) >>> y = Symbol('y', even=True)
打印完整假设信息:
>>> print_tree(y**x) Pow: y**x +-Symbol: y | algebraic: True | commutative: True | complex: True | even: True | extended_real: True | finite: True | hermitian: True | imaginary: False | infinite: False | integer: True | irrational: False | noninteger: False | odd: False | rational: True | real: True | transcendental: False +-Symbol: x algebraic: True commutative: True complex: True even: False extended_nonzero: True extended_real: True finite: True hermitian: True imaginary: False infinite: False integer: True irrational: False noninteger: False nonzero: True odd: True rational: True real: True transcendental: False zero: False
隐藏假设:
>>> print_tree(y**x, assumptions=False) Pow: y**x +-Symbol: y +-Symbol: x
参见
预览#
一个有用的函数是 preview :
- sympy.printing.preview.preview(expr, output='png', viewer=None, euler=True, packages=(), filename=None, outputbuffer=None, preamble=None, dvioptions=None, outputTexFile=None, extra_preamble=None, fontsize=None, **latex_settings)[源代码]#
以PNG、DVI、PostScript或PDF格式查看表达式或LaTeX标记。
如果expr参数是一个表达式,它将被导出到LaTeX,然后使用可用的TeX发行版进行编译。第一个参数“expr”也可能是 Latex 字符串。然后,该函数将针对给定的输出格式运行相应的查看器,或使用用户定义的格式。默认情况下生成png输出。
默认情况下,漂亮的欧拉字体用于排版(它们用于排版众所周知的“具体数学”书籍)。要想成功,你需要欧莱夫姆斯蒂'LaTeX样式(在Debian/Ubuntu中,安装texlive-fonts额外包)。如果您喜欢默认的AMS字体或您的系统缺少“eulervm”LaTeX包,则取消设置“euler”关键字参数。
要使用查看器自动检测,假设对于“png”输出,问题
>>> from sympy import symbols, preview, Symbol >>> x, y = symbols("x,y")
>>> preview(x + y, output='png')
这将默认选择“pyglet”。要选择另一个,请执行以下操作:
>>> preview(x + y, output='png', viewer='gimp')
“png”格式被认为是特殊格式。对于所有其他格式,规则略有不同。作为一个例子,我们将采用“dvi”输出格式。如果你愿意跑
>>> preview(x + y, output='dvi')
then 'view' will look for available 'dvi' viewers on your system (predefined in the function, so it will try evince, first, then kdvi and xdvi). If nothing is found, it will fall back to using a system file association (via
openandxdg-open). To always use your system file association without searching for the above readers, use>>> from sympy.printing.preview import system_default_viewer >>> preview(x + y, output='dvi', viewer=system_default_viewer)
If this still does not find the viewer you want, it can be set explicitly.
>>> preview(x + y, output='dvi', viewer='superior-dvi-viewer')
This will skip auto-detection and will run user specified 'superior-dvi-viewer'. If
viewfails to find it on your system it will gracefully raise an exception.You may also enter
'file'for the viewer argument. Doing so will cause this function to return a file object in read-only mode, iffilenameis unset. However, if it was set, then 'preview' writes the generated file to this filename instead.There is also support for writing to a
io.BytesIOlike object, which needs to be passed to theoutputbufferargument.>>> from io import BytesIO >>> obj = BytesIO() >>> preview(x + y, output='png', viewer='BytesIO', ... outputbuffer=obj)
可以通过设置“preamble”关键字参数自定义LaTeX前导码。这可以用来设置不同的字体大小,使用自定义文档类或导入特定的LaTeX软件包。
>>> preamble = "\\documentclass[10pt]{article}\n" \ ... "\\usepackage{amsmath,amsfonts}\\begin{document}" >>> preview(x + y, output='png', preamble=preamble)
It is also possible to use the standard preamble and provide additional information to the preamble using the
extra_preamblekeyword argument.>>> from sympy import sin >>> extra_preamble = "\\renewcommand{\\sin}{\\cos}" >>> preview(sin(x), output='png', extra_preamble=extra_preamble)
If the value of 'output' is different from 'dvi' then command line options can be set ('dvioptions' argument) for the execution of the 'dvi'+output conversion tool. These options have to be in the form of a list of strings (see
subprocess.Popen).Additional keyword args will be passed to the
latex()call, e.g., thesymbol_namesflag.>>> phidd = Symbol('phidd') >>> preview(phidd, symbol_names={phidd: r'\ddot{\varphi}'})
For post-processing the generated TeX File can be written to a file by passing the desired filename to the 'outputTexFile' keyword argument. To write the TeX code to a file named
"sample.tex"and run the default png viewer to display the resulting bitmap, do>>> preview(x + y, outputTexFile="sample.tex")
实现-帮助程序类/函数#
- sympy.printing.conventions.split_super_sub(text)[源代码]#
将符号名称拆分为名称、上标和下标
符号名的第一部分被认为是它的实际“名称”,后跟super和subscripts。每个上标前面都有一个“^”字符或“uu”。每个下标前面都有一个“”字符。这三个返回值是实际名称、带有上标的列表和带有下标的列表。
实例
>>> from sympy.printing.conventions import split_super_sub >>> split_super_sub('a_x^1') ('a', ['1'], ['x']) >>> split_super_sub('var_sub1__sup_sub2') ('var', ['sup'], ['sub1', 'sub2'])
CodePrinter#
这个类是实现代码打印功能的其他类的基类,另外还列出了许多无法轻松转换为C或Fortran的函数。
- class sympy.printing.codeprinter.CodePrinter(settings=None)[源代码]#
代码打印子类的基类。
- printmethod: str = '_sympystr'#
- doprint(expr, assign_to=None)[源代码]#
Print the expression as code.
- 参数:
expr :表达式
The expression to be printed.
assign_to : Symbol, string, MatrixSymbol, list of strings or Symbols (optional)
If provided, the printed code will set the expression to a variable or multiple variables with the name or names given in
assign_to.
优先#
- sympy.printing.precedence.PRECEDENCE = {'Add': 40, 'And': 30, 'Atom': 1000, 'BitwiseAnd': 38, 'BitwiseOr': 36, 'BitwiseXor': 37, 'Func': 70, 'Lambda': 1, 'Mul': 50, 'Not': 100, 'Or': 20, 'Pow': 60, 'Relational': 35, 'Xor': 10}#
某些基本类型的默认优先级值。
- sympy.printing.precedence.PRECEDENCE_VALUES = {'Add': 40, 'And': 30, 'Equality': 50, 'Equivalent': 10, 'Function': 70, 'HadamardPower': 60, 'HadamardProduct': 50, 'Implies': 10, 'KroneckerProduct': 50, 'MatAdd': 40, 'MatPow': 60, 'MatrixSolve': 50, 'Mod': 50, 'NegativeInfinity': 40, 'Not': 100, 'Or': 20, 'Pow': 60, 'Relational': 35, 'Sub': 40, 'TensAdd': 40, 'TensMul': 50, 'Unequality': 50, 'Xor': 10}#
为某些类指定优先值的字典。这些值被当作是继承的,所以不是每个类都必须在这里命名。
- sympy.printing.precedence.PRECEDENCE_FUNCTIONS = {'Float': <function precedence_Float>, 'FracElement': <function precedence_FracElement>, 'Integer': <function precedence_Integer>, 'Mul': <function precedence_Mul>, 'PolyElement': <function precedence_PolyElement>, 'Rational': <function precedence_Rational>, 'UnevaluatedExpr': <function precedence_UnevaluatedExpr>}#
有时给类分配一个固定的优先级值是不够的。然后可以在这个字典中插入一个函数,该函数以这个类的一个实例作为参数并返回适当的优先值。
漂亮的打印实现助手#
- sympy.printing.pretty.pretty_symbology.U(name)[源代码]#
Get a unicode character by name or, None if not found.
This exists because older versions of Python use older unicode databases.
- sympy.printing.pretty.pretty_symbology.pretty_use_unicode(flag=None)[源代码]#
设置pretty printer是否默认使用unicode
以下两个函数返回输入的希腊字母的Unicode版本。
- sympy.printing.pretty.pretty_symbology.greek_letters = ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lamda', 'mu', 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega']#
内置可变序列。
如果没有给定参数,则构造函数将创建一个新的空列表。如果指定,则参数必须是ITerable。
- sympy.printing.pretty.pretty_symbology.digit_2txt = {'0': 'ZERO', '1': 'ONE', '2': 'TWO', '3': 'THREE', '4': 'FOUR', '5': 'FIVE', '6': 'SIX', '7': 'SEVEN', '8': 'EIGHT', '9': 'NINE'}#
- sympy.printing.pretty.pretty_symbology.symb_2txt = {'(': 'LEFT PARENTHESIS', ')': 'RIGHT PARENTHESIS', '+': 'PLUS SIGN', '-': 'MINUS', '=': 'EQUALS SIGN', '[': 'LEFT SQUARE BRACKET', ']': 'RIGHT SQUARE BRACKET', 'int': 'INTEGRAL', 'sum': 'SUMMATION', '{': 'LEFT CURLY BRACKET', '{}': 'CURLY BRACKET', '}': 'RIGHT CURLY BRACKET'}#
以下函数返回字符的Unicode下标/上标版本。
- sympy.printing.pretty.pretty_symbology.sub = {'(': '₍', ')': '₎', '+': '₊', '-': '₋', '0': '₀', '1': '₁', '2': '₂', '3': '₃', '4': '₄', '5': '₅', '6': '₆', '7': '₇', '8': '₈', '9': '₉', '=': '₌', 'a': 'ₐ', 'beta': 'ᵦ', 'chi': 'ᵪ', 'e': 'ₑ', 'gamma': 'ᵧ', 'h': 'ₕ', 'i': 'ᵢ', 'k': 'ₖ', 'l': 'ₗ', 'm': 'ₘ', 'n': 'ₙ', 'o': 'ₒ', 'p': 'ₚ', 'phi': 'ᵩ', 'r': 'ᵣ', 'rho': 'ᵨ', 's': 'ₛ', 't': 'ₜ', 'u': 'ᵤ', 'v': 'ᵥ', 'x': 'ₓ'}#
- sympy.printing.pretty.pretty_symbology.sup = {'(': '⁽', ')': '⁾', '+': '⁺', '-': '⁻', '0': '⁰', '1': '¹', '2': '²', '3': '³', '4': '⁴', '5': '⁵', '6': '⁶', '7': '⁷', '8': '⁸', '9': '⁹', '=': '⁼', 'i': 'ⁱ', 'n': 'ⁿ'}#
以下函数返回Unicode垂直对象。
以下常量用于呈现根和分数。
- sympy.printing.pretty.pretty_symbology.root = {2: '√', 3: '∛', 4: '∜'}#
- sympy.printing.pretty.pretty_symbology.frac = {(1, 2): '½', (1, 3): '⅓', (1, 4): '¼', (1, 5): '⅕', (1, 6): '⅙', (1, 8): '⅛', (2, 3): '⅔', (2, 5): '⅖', (3, 4): '¾', (3, 5): '⅗', (3, 8): '⅜', (4, 5): '⅘', (5, 6): '⅚', (5, 8): '⅝', (7, 8): '⅞'}#
以下常量/函数用于呈现原子和符号。
- sympy.printing.pretty.pretty_symbology.atoms_table = {'And': '∧', 'Arrow': '→', 'ArrowFromBar': '↦', 'Complexes': 'ℂ', 'Contradiction': '┬', 'Dagger': '†', 'Degree': '°', 'Differential': 'ⅆ', 'Dots': '…', 'ElementOf': '∈', 'EmptySequence': 'EmptySequence', 'EmptySet': '∅', 'Equiv': '⇔', 'Exp1': 'ℯ', 'IdentityMatrix': '𝕀', 'ImaginaryUnit': 'ⅈ', 'Implies': '⇔', 'Infinity': '∞', 'Integers': 'ℤ', 'Intersection': '∩', 'Modifier Letter Low Ring': '˳', 'Multiplication': '×', 'Nand': '⊼', 'Naturals': 'ℕ', 'Naturals0': 'ℕ₀', 'NegativeInfinity': '-∞', 'Nor': '⊽', 'Not': '¬', 'NotArrow': '↛', 'NotEquiv': '⇎', 'NotImplies': '⇎', 'OneMatrix': '𝟙', 'Or': '∨', 'Pi': 'π', 'Rationals': 'ℚ', 'Reals': 'ℝ', 'Ring': '∘', 'SmallElementOf': '∊', 'SuperscriptMinus': '⁻', 'SuperscriptPlus': '⁺', 'SymmetricDifference': '∆', 'Tautology': '┴', 'TensorProduct': '⨂', 'Union': '∪', 'Universe': '𝕌', 'Xor': '⊻', 'ZeroMatrix': '𝟘'}#
- sympy.printing.pretty.pretty_symbology.pretty_atom(atom_name, default=None, printer=None)[源代码]#
返回原子的漂亮表示
- sympy.printing.pretty.pretty_symbology.annotated(letter)[源代码]#
返回信件的样式图
letter,以及如何在其上放置注释(左、右的超级和下标)的信息。看到了吗漂亮极了函数u print_meijerg,u print_hyper了解如何使用此信息。
Jurjen Bos的PretyPrinter。(我讨厌垃圾邮件发送者:请在pietjepuk314的背面给我发邮件库奥克。乌海). 所有对象都有一个创建“stringPict”的方法,该方法可以在str方法中用于漂亮的打印。
- Jason Gedge更新(电子邮件<my last name>at cs mun ca)
terminal_string()方法
小修小改(主要是为了美观)
- TODO:
允许左/中/右对齐选项用于上方/下方,顶部/中心/底部对齐选项用于左/右
- class sympy.printing.pretty.stringpict.stringPict(s, baseline=0)[源代码]#
ASCII图片。图片表示为等长字符串列表。
- below(*args)[源代码]#
把图片放在这张图片下面。返回stringPict的字符串基线参数。基线是顶部图片的基线
实例
>>> from sympy.printing.pretty.stringpict import stringPict >>> print(stringPict("x+3").below( ... stringPict.LINE, '3')[0]) x+3 --- 3
- parens(left='(', right=')', ifascii_nougly=False)[源代码]#
在self后面加上括号。返回stringPict的字符串基线参数。
left或right可以是None或空字符串,这意味着“从那一侧没有paren”
- right(*args)[源代码]#
把照片放在这个旁边。返回stringPict的字符串基线参数。(多行)字符串是允许的,并且基线为0。
实例
>>> from sympy.printing.pretty.stringpict import stringPict >>> print(stringPict("10").right(" + ",stringPict("1\r-\r2",1))[0]) 1 10 + - 2
- class sympy.printing.pretty.stringpict.prettyForm(s, baseline=0, binding=0, unicode=None)[源代码]#
stringPict类的扩展,它了解基本的数学应用程序,优化双减号。
“绑定”解释如下:
ATOM this is an atom: never needs to be parenthesized FUNC this is a function application: parenthesize if added (?) DIV this is a division: make wider division if divided POW this is a power: only parenthesize if exponent MUL this is a multiplication: parenthesize if powered ADD this is an addition: parenthesize if multiplied or powered NEG this is a negative number: optimize if added, parenthesize if multiplied or powered OPEN this is an open object: parenthesize if added, multiplied, or powered (example: Piecewise)
点打印#
- sympy.printing.dot.dotprint(expr, styles=((<class 'sympy.core.basic.Basic'>, {'color': 'blue', 'shape': 'ellipse'}), (<class 'sympy.core.expr.Expr'>, {'color': 'black'})), atom=<function <lambda>>, maxdepth=None, repeat=True, labelfunc=<class 'str'>, **kwargs)[源代码]#
SymPy表达式树的点描述
- 参数:
风格 :由(类,映射)组成的列表列表,可选
不同类别的样式。
默认值为
( (Basic, {'color': 'blue', 'shape': 'ellipse'}), (Expr, {'color': 'black'}) )
atom :功能,可选
用于确定arg是否为原子的函数。
一个好的选择是
lambda x: not x.args.默认值为
lambda x: not isinstance(x, Basic).最大深度 :整数,可选
最大深度。
默认值为
None,意思是没有限制。重复 :布尔值,可选
是否为公共子表达式使用不同的节点。
默认值为
True.例如,对于
x + x*y具有repeat=True,它将有两个节点用于x;与repeat=False,它将有一个节点。警告
即使一个节点在同一个对象中出现两次
x在里面Pow(x, x),它仍将只出现一次。因此,与repeat=False,对象的箭头数可能不等于它的参数数。labelfunc公司 :功能,可选
为给定叶节点创建标签的函数。
默认值为
str.另一个好的选择是
srepr.例如
str,叶节点x + 1有标签,x和1. 用srepr,它们有标签Symbol('x')和Integer(1).**kwargs :可选
其他关键字参数作为图形的样式包括在内。
实例
>>> from sympy import dotprint >>> from sympy.abc import x >>> print(dotprint(x+2)) digraph{ # Graph style "ordering"="out" "rankdir"="TD" ######### # Nodes # ######### "Add(Integer(2), Symbol('x'))_()" ["color"="black", "label"="Add", "shape"="ellipse"]; "Integer(2)_(0,)" ["color"="black", "label"="2", "shape"="ellipse"]; "Symbol('x')_(1,)" ["color"="black", "label"="x", "shape"="ellipse"]; ######### # Edges # ######### "Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)"; "Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)"; }