SymPy-1-13-中文文档-二十二-

SymPy 1.13 中文文档(二十二)

原文:docs.sympy.org/latest/index.html

打印

原文链接:docs.sympy.org/latest/modules/printing.html

请参阅教程中的 Printing 部分,了解有关打印的介绍。

本指南记录了 SymPy 中的打印系统及其内部工作原理。

打印机类

打印子系统驱动程序

SymPy 的打印系统工作方式如下:任何表达式都可以传递给指定的打印机,然后该打印机负责返回该表达式的适当表示。

基本概念如下:

  1. 如果对象知道如何打印,请让其自行打印。

  2. 选择打印机中定义的最佳方法。

  3. 作为后备,对于打印机,请使用 emptyPrinter 方法。

哪种方法负责打印?

整个打印过程是通过在您想要使用的打印机上调用.doprint(expr)来启动的。此方法寻找可以按照打印机定义的给定样式打印给定表达式的适当方法。在寻找方法时,它遵循以下步骤:

  1. 如果对象知道如何打印,请让其自行打印。

    打印机在每个对象中寻找特定的方法。该方法的名称取决于特定的打印机,并在Printer.printmethod下定义。例如,StrPrinter 调用_sympystr,而 LatexPrinter 调用_latex。请查看您想要使用的打印机的文档。方法的名称在那里指定。

    这是在 sympy 中进行打印的原始方法。每个类都有自己的 latex、mathml、str 和 repr 方法,但事实证明,如果所有方法都分散在那么远,要生成高质量的打印机是困难的。因此,所有打印代码都合并到不同的打印机中,这对于内置的 SymPy 对象效果很好,但对于用户定义的类来说,这并不方便修补打印机。

  2. 选择在打印机中定义的最佳方法。

    打印机遍历 expr 类(类+其基类),并尝试将工作分派给_print_<EXPR_CLASS>

    例如,假设我们有以下类层次结构:

     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等等。

  3. 作为备选,对于打印机,请使用 emptyPrinter 方法。

    作为后备,将使用self.emptyPrinter来处理表达式。如果在打印机子类中未定义,则这将与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 打印输出。这是通过重写`Mod`的`_latex`方法完成的。

```py
>>> 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)来打印表达式的子组件非常重要。错误包括:

  1. 使用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) 
    

    当将mode参数传递给打印机时,这种方法会失败:

    >>> 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)}$ 
    
  2. 使用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)} 
    
  3. 使用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) 
    

    这会导致子对象中的所有设置被丢弃。例如,完整精度设置,显示浮点数的完整精度被忽略:

    >>> 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(还可以查看其源代码):

class sympy.printing.printer.Printer(settings=None)

通用打印机

它的工作是为轻松实现新打印机提供基础设施。

如果您想为自定义打印机或自定义类的自定义打印方法定义自定义打印机,请参见上面的示例:printer_example。

printmethod: str = None
_print(expr, **kwargs) → str

内部分发器

尝试以下概念来打印表达式:

  1. 如果对象知道如何打印自身,则让对象自己打印。

  2. 使用打印机中定义的最合适方法。

  3. 作为回退,使用打印机的 emptyPrinter 方法。

doprint(expr)

返回表达式的打印机表示(作为字符串)

classmethod set_global_settings(**settings)

设置系统范围的打印设置。

PrettyPrinter 类

漂亮打印子系统由PrettyPrinter类在sympy.printing.pretty.pretty中实现,从Printer派生。它依赖于模块sympy.printing.pretty.stringPictsympy.printing.pretty.pretty_symbology来渲染漂亮的公式。

模块stringPict提供了基类stringPict和派生类prettyForm,用于轻松创建和操作跨多行的公式。

模块pretty_symbology提供了构造 2D 形状(hline、vline 等)的基元,以及一种在可能时自动使用 Unicode 的技术。

class sympy.printing.pretty.pretty.PrettyPrinter(settings=None)

打印机,将表达式转换为 2D ASCII 艺术图。

printmethod: str = '_pretty'
sympy.printing.pretty.pretty.pretty(expr, *, order=None, full_prec='auto', use_unicode=True, wrap_line=True, num_columns=None, use_unicode_sqrt_char=True, root_notation=True, mat_symbol_style='plain', imaginary_unit='i', perm_cyclic=True)

返回包含表达式的美化形式的字符串。

有关关键字参数的信息,请参见 pretty_print 函数。

sympy.printing.pretty.pretty.pretty_print(expr, **kwargs)

以漂亮的形式打印表达式。

pprint 只是此函数的快捷方式。

参数:

expr:表达式

要打印的表达式。

wrap_line:bool,可选(默认为 True)

启用/禁用换行。

num_columns:int 或 None,可选(默认为 None)

在进行换行之前的列数(默认为 None,读取终端宽度),在不使用终端时很有用。

use_unicode:bool 或 None,可选(默认为 None)

使用 Unicode 字符,如希腊字母π,而不是字符串 pi。

full_prec:bool 或字符串,可选(默认为“auto”)

使用完整精度。

order:bool 或字符串,可选(默认为 None)

设置为“none”以用于长表达式,如果慢则默认为 None。

use_unicode_sqrt_char:bool,可选(默认为 True)

使用紧凑的单字符平方根符号(在不歧义的情况下)。

root_notation:布尔值,可选(默认为 True)

设置为“False”以以分数形式打印形式为 1/n 的指数。默认情况下,指数以根式形式打印。

mat_symbol_style:字符串,可选(默认为“plain”)

设置为“粗体”以使用粗体数学符号打印 MatrixSymbols。默认情况下使用标准字体。

imaginary_unit:字符串,可选(默认为”i“)

在 use_unicode 为 True 时使用的虚数单位的字母。可以是“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)

一个打印机,用于将 Python 表达式转换为 C 代码字符串

printmethod: str = '_ccode'
indent_code(code)

接受代码字符串或代码行列表

class sympy.printing.c.C99CodePrinter(settings=None)
printmethod: str = '_ccode'
sympy.printing.c.ccode(expr, assign_to=None, standard='c99', **settings)

将表达式转换为 C 代码的字符串

参数:

expr:Expr

要转换的 SymPy 表达式。

assign_to:可选

给定时,该参数用作分配给表达式的变量的名称。可以是字符串,SymbolMatrixSymbolIndexed类型。这在换行或生成多行语句的表达式中很有帮助。

standard:字符串,可选

字符串,指定标准。如果您的编译器支持更现代的标准,您可以将其设置为“c99”,以允许打印机使用更多的数学函数。[default='c89']。

precision:整数,可选

例如π的数字精度[default=17]。

user_functions:字典,可选

一个字典,其键是FunctionClassUndefinedFunction实例的字符串表示,值是它们期望的 C 字符串表示。或者,字典值可以是元组列表,即[(argument_test, cfunction_string)]或[(argument_test, cfunction_formater)]。请参阅下面的示例。

dereference:可迭代对象,可选

应在打印的代码表达式中取消引用的符号的可迭代项。这些将是传递给函数的地址的值。例如,如果dereference=[a],则生成的代码将打印(*a)而不是a

human:布尔值,可选

如果为 True,则结果是一个可能包含一些常量声明的单个字符串。如果为 False,则返回元组(symbols_to_declare,not_supported_functions,code_text)。[default=True]。

contract:布尔值,可选

如果为 True,则假定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)' 

可以通过将{“type”:“function”}的字典传递给user_functions关键字来为某些类型定义简单的自定义打印。或者,字典值可以是元组列表,即[(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]);' 

矩阵也受支持,但必须向 assign_to 提供相同维度的 MatrixSymbol。注意,任何可以正常生成的表达式也可以存在于矩阵内:

>>> 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); 
sympy.printing.c.print_ccode(expr, **settings)

打印给定表达式的 C 表示。 ## C++ 代码打印机

此模块包含用于 C++ 代码的打印机,即将 SymPy 表达式转换为 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) 
class sympy.printing.cxx.CXX98CodePrinter(settings=None)
printmethod: str = '_cxxcode'
class sympy.printing.cxx.CXX11CodePrinter(settings=None)
printmethod: str = '_cxxcode'
sympy.printing.codeprinter.cxxcode(expr, assign_to=None, standard='c++11', **settings)

ccode() 的 C++ 等效物。 ## 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)² + cos(x)²
>>> print_rcode(2*x + cos(x), assign_to="result")
result = 2*x + cos(x);
>>> print_rcode(Abs(x**2))
abs(x²) 
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={})

将 SymPy 表达式转换为 R 代码字符串的打印机

printmethod: str = '_rcode'
indent_code(code)

接受代码字符串或代码行列表

sympy.printing.rcode.rcode(expr, assign_to=None, **settings)

将表达式转换为 r 代码字符串

参数:

expr:表达式

要转换的 SymPy 表达式。

assign_to:可选项

给定时,将其用作分配表达式的变量名称。可以是字符串、SymbolMatrixSymbolIndexed 类型。在换行或生成多行语句的表达式时非常有用。

精度:整数,可选项

诸如 pi 等数字的精度 [默认=15]。

user_functions:字典,可选项

字典,其键是 FunctionClassUndefinedFunction 实例的字符串表示,值是其期望的 R 字符串表示。或者,字典值可以是元组列表,即 [(argument_test, rfunction_string)] 或 [(argument_test, rfunction_formater)]。查看以下示例。

human:bool,可选

如果为 True,则结果是一个可能包含一些常数声明的单个字符串。如果为 False,则以 (symbols_to_declare, not_supported_functions, code_text) 元组形式返回相同的信息。[默认=True]。

contract: bool,可选

如果为 True,则假定 Indexed 实例遵守张量收缩规则,并生成相应的索引嵌套循环。设置 contract=False 将不生成循环,而是由用户负责在代码中提供索引的值。[默认=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);' 

可以通过将 {“type” : “function”} 字典传递给 user_functions 关键字来定义某些类型的简单自定义打印。或者,字典值可以是元组列表,即 [(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]);' 

也支持矩阵,但必须提供相同维度的 MatrixSymbolassign_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²;
A[1] = ifelse(x > 0,x + 1,x);
A[2] = sin(x); 
sympy.printing.rcode.print_rcode(expr, **settings)

打印给定表达式的 R 表示。

Fortran 打印

fcode 函数将 sympy 表达式转换为 Fortran 代码。其主要目的是减少手动翻译长数学表达式的负担。因此,生成的表达式也应该不需要(或者非常少的)手动调整即可进行编译。fcode 的可选参数可用于微调其行为,以使结果不再需要手动更改。

sympy.printing.fortran.fcode(expr, assign_to=None, **settings)

将表达式转换为 Fortran 代码的字符串

参数:

expr : Expr

一个 SymPy 表达式将被转换。

assign_to : 可选

当给出时,该参数被用作分配表达式的变量名。可以是字符串,SymbolMatrixSymbolIndexed 类型。对于生成多行语句或者行折叠的表达式来说非常有用。

precision : 整数,可选

已弃用。使用 type_mappings 替代。诸如 pi 这样的数字的精度 [默认=17]。

user_functions : 字典,可选

一个字典,其中键是 FunctionClass 实例,值是它们的字符串表示。或者,字典值可以是元组列表,例如 [(argument_test, cfunction_string)]。详见下面的例子。

human : bool, 可选

如果为 True,则结果是一个包含一些常数声明的单个字符串,用于表示数字符号。如果为 False,则相同的信息以 (symbols_to_declare, not_supported_functions, code_text) 的元组形式返回。[默认=True]。

contract: bool, 可选

如果为 True,则假定 Indexed 实例遵守张量缩并规则,并生成相应的索引嵌套循环。设置 contract=False 将不会生成循环,而是要求用户在代码中为索引提供值。[默认=True]。

source_format : 可选

源格式可以是“fixed”或“free”。[默认='fixed']

standard : 整数,可选

要遵循的 Fortran 标准。这是指定的整数。可接受的标准为 66、77、90、95、2003 和 2008。默认是 77。请注意,目前在内部唯一的区分是在 95 之前的标准和 95 及之后的标准之间。随着添加更多功能,这可能会发生变化。

name_mangling : 布尔值,可选

如果为 True,则在不区分大小写的 Fortran 中,会通过在末尾附加不同数量的 _ 来搞乱变量的命名。如果为 False,则 SymPy 不会干预变量的命名。[默认=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))' 

矩阵也受支持,但必须向 assign_to 提供相同维度的 MatrixSymbol。请注意,任何可以正常生成的表达式也可以存在于矩阵内:

>>> 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) 
sympy.printing.fortran.print_fcode(expr, **settings)

打印给定表达式的 Fortran 表示。

详细信息请参见 fcode 的可选参数含义。

class sympy.printing.fortran.FCodePrinter(settings=None)

一个打印机,将 SymPy 表达式转换为 Fortran 代码字符串

printmethod: str = '_fcode'
indent_code(code)

接受代码字符串或代码行列表

两个基本示例:

>>> 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 中缺乏条件运算符。可以通过设置 standard=95 来支持使用 Fortran 95 中引入的 merge 函数进行内联条件支持:

>>> print(fcode(Piecewise((x,x<1),(x**2,True)), standard=95))
 merge(x, x**2, x < 1) 

如果表达式中存在 Indexed 对象,则生成循环。这也需要使用 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 

在带有 Indexed 对象的表达式中,重复的指标被解释为求和。例如,可以生成矩阵的迹的代码。

>>> print(fcode(A[i, i], assign_to=x))
 x = 0
 do i = 1, m
 x = x + A(i, i)
 end do 

默认情况下,如 piE 等数字符号将被检测并定义为 Fortran 参数。可以使用精度参数调整常数的精度。使用 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 

然而,当未提供 user_functions 参数时,fcode默认会引发异常,但如果用户打算提供具有相同名称的函数,则仍可以生成代码,方法是通过传递选项strict=False。然后,代码中包含一条评论,通知用户存在的问题:

>>> 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 打印

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)

expr转换为一串 smtlib 代码。

参数:

expr:Expr | List[Expr]

要转换的 SymPy 表达式或系统。

自动断言:布尔值,可选

如果为 false,则不修改 expr 并仅生成 expr 的 S 表达式等价物。如果为 true,则假设 expr 是一个系统,并断言每个布尔元素。

自动声明:布尔值,可选

如果为 false,则不要为 expr 中使用的符号生成声明。如果为 true,则根据 symbol_table 预先生成 expr 中使用的变量的所有必要声明。

精度:整数,可选

对于如 pi 等数字的evalf(..)精度。

符号表:字典,可选

一个字典,其中键为SymbolFunction实例,值为它们的 Python 类型,如boolintfloatCallable[...]。如果不完整,将尝试从expr推断类型。

已知类型:字典,可选

一个字典,其中键为boolintfloat等,值为它们对应的 SMT 类型名称。如果未给出,将使用与多个求解器兼容的部分列表。

已知函数:字典,可选

一个字典,其中键为FunctionRelationalBooleanFunctionExpr实例,值为它们的 SMT 字符串表示。如果未给出,将使用针对 dReal 求解器优化的部分列表(但与其他求解器兼容)。

已知常量:字典,可选

一个字典,其中键为NumberSymbol实例,值为它们的 SMT 变量名。在使用此功能时,必须格外小心,以避免用户符号与列出的常量之间的命名冲突。如果未给出,常量将被内联展开,例如3.14159而非MY_SMT_VARIABLE_FOR_PI

前缀表达式:列表,可选

一个列表的列表,其中包含要转换为 SMTLib 并附加到输出的str和/或表达式。

后缀表达式:列表,可选

一个列表的列表,其中包含要转换为 SMTLib 并作为输出前缀的str和/或表达式。

日志警告:lambda 函数,可选

一个用于记录在可能存在风险操作期间发出的所有警告的函数。在 SMT 求解中,健全性是一项核心价值,因此记录所有假设是很好的。

示例

>>> 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)))' 

Piecewise表达式默认使用ite表达式实现。请注意,如果Piecewise缺少由(expr, True)表示的默认项,则会引发错误。这是为了防止生成可能不会评估为任何内容的表达式。

>>> 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))' 

可通过将 PythonType:“SMT Name”的字典传递给known_typesknown_constantsknown_functions kwargs 来定义某些类型的自定义打印。

>>> 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 代码打印

```py
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.mathematica.MCodePrinter(settings={})

用于将 Python 表达式转换为 Wolfram Mathematica 代码的打印机

printmethod: str = '_mcode'
sympy.printing.mathematica.mathematica_code(expr, **settings)

将表达式转换为 Wolfram Mathematica 代码的字符串

示例

>>> from sympy import mathematica_code as mcode, symbols, sin
>>> x = symbols('x')
>>> mcode(sin(x).series(x).removeO())
'(1/120)*x⁵ - 1/6*x³ + x' 
```  ## Maple 代码打印

```py
class sympy.printing.maple.MapleCodePrinter(settings=None)

将 SymPy 表达式转换为 Maple 代码的打印机。

printmethod: str = '_maple'
sympy.printing.maple.maple_code(expr, assign_to=None, **settings)

expr转换为 Maple 代码的字符串。

参数:

expr : 表达式

要转换的 SymPy 表达式。

assign_to : 可选

如果提供,则该参数用作分配表达式的变量名。可以是字符串,SymbolMatrixSymbolIndexed类型。这对于生成多行语句的表达式非常有帮助。

precision : 整数,可选

像π这样的数字的精度[默认=16]。

user_functions : 字典,可选

一个字典,其键为FunctionClass实例,值为它们的字符串表示。或者,字典值可以是元组的列表,即[(argument_test, cfunction_string)]。请参阅下面的示例。

human : 布尔值,可选

如果为 True,则结果是一个可能包含一些常数声明的单字符串。如果为 False,则相同的信息以(symbols_to_declare, not_supported_functions, code_text)元组形式返回。[默认=True]。

contract: bool,可选

如果为 True,则假定Indexed实例遵守张量缩并规则,并生成相应的索引嵌套循环。设置 contract=False 将不生成循环,而是由用户在代码中提供索引的值。[默认=True]。

inline: bool,可选

如果为 True,我们会尝试创建单语句代码而不是多语句。[默认=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 代码打印

```py
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={})

“一个打印机,将 Python 表达式转换为 JavaScript 代码字符串

printmethod: str = '_javascript'
indent_code(code)

接受代码字符串或代码行列表

sympy.printing.jscode.jscode(expr, assign_to=None, **settings)

将表达式转换为 JavaScript 代码的字符串

参数:

expr : 表达式

要转换的 SymPy 表达式。

assign_to : 可选

如果提供,则该参数用作分配表达式的变量名。可以是字符串,SymbolMatrixSymbolIndexed类型。在换行或生成多行语句的表达式中很有帮助。

precision : 整数,可选

像π这样的数字的精度[默认=15]。

user_functions : 字典,可选

一个字典,其中键是 FunctionClass 实例,值是它们的字符串表示。或者,字典值可以是元组列表,即 [(argument_test, js_function_string)]。请参阅以下示例。

human : bool, 可选

如果为 True,则结果是一个单独的字符串,其中可能包含一些常数声明用于数字符号。如果为 False,则返回一个元组 (symbols_to_declare, not_supported_functions, code_text),其中包含相同的信息。[默认=True]。

contract: bool, 可选

如果为 True,则假定 Indexed 实例遵循张量收缩规则,并生成相应的嵌套索引循环。设置 contract=False 将不生成循环,而是由用户负责在代码中为索引提供值。[默认=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]);' 

还支持矩阵,但必须为 assign_to 提供相同维度的 MatrixSymbol。请注意,任何通常可以生成的表达式也可以存在于矩阵中:

>>> 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); 
```  ## Julia 代码打印

```py
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']

内置可变序列。

如果未提供参数,则构造函数创建一个新的空列表。如果指定了参数,则必须是可迭代的。

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'
indent_code(code)

接受代码字符串或代码行列表

sympy.printing.julia.julia_code(expr, assign_to=None, **settings)

将 (expr) 转换为 Julia 代码的字符串。

参数:

expr : Expr

要转换的 SymPy 表达式。

assign_to : 可选

如果提供了此参数,则用作分配表达式的变量名。可以是字符串、SymbolMatrixSymbolIndexed 类型。这对生成多行语句的表达式很有帮助。

precision : 整数, 可选

诸如 pi 的数字的精度 [默认=16]。

user_functions : dict, 可选

一个字典,其中键是 FunctionClass 实例,值是它们的字符串表示。或者,字典值可以是元组列表,即 [(argument_test, cfunction_string)]。请参阅以下示例。

human : bool, 可选

如果为 True,则结果是一个可能包含一些常数声明的单字符串符号。如果为 False,则将在一个元组中返回相同的信息(symbols_to_declare, not_supported_functions, code_text)。[默认为 True]。

contract: bool,可选

如果为 True,则假设 Indexed 实例遵守张量缩并规则,并生成相应的索引嵌套循环。设置 contract=False 将不生成循环,而是由用户负责在代码中提供索引的值。[默认为 True]。

inline: bool,可选

如果为 True,则尝试创建单语句代码而不是多语句。[默认为 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' 

该类使用多个规则来决定使用哪个符号来表示乘积。纯数字使用 “”,符号使用 “.”,而 MatrixSymbols 使用 “”。HadamardProduct 可用于指定两个 MatrixSymbols 的分量乘法 “.”。目前没有简单的方法来指定标量符号,因此有时代码可能会存在一些小的美观问题。例如,假设 x 和 y 是标量,A 是一个矩阵,则虽然人类程序员可能会写 “(x²y)A³”,我们生成的是:

>>> 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 kwarg 来为某些类型定义自定义打印。或者,字典值可以是元组列表,即 [(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])' 
```  ## Octave(和 Matlab)代码打印

```py
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']

内置可变序列。

如果未提供参数,则构造函数将创建一个新的空列表。如果指定了参数,则必须是可迭代的。

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={})

打印机将表达式转换为 Octave/Matlab 代码字符串。

printmethod: str = '_octave'
indent_code(code)

接受代码字符串或代码行列表。

sympy.printing.octave.octave_code(expr, assign_to=None, **settings)

将 (expr) 转换为 Octave(或 Matlab)代码字符串。

字符串使用 Matlab 兼容的 Octave 语言子集。

参数:

expr : 表达式

要转换的 SymPy 表达式。

assign_to : 可选

给定时,参数用作分配表达式的变量名称。可以是字符串,SymbolMatrixSymbolIndexed类型。对于生成多行语句的表达式非常有帮助。

precision : 整数,可选

数字的精度,例如 pi [默认=16]。

user_functions : dict, 可选

字典,其中键是FunctionClass实例,值是它们的字符串表示。或者,字典值可以是元组列表,即[(argument_test, cfunction_string)]。有关示例,请参见下文。

human : bool, 可选

如果为 True,则结果是一个可能包含一些常数声明的单个字符串。如果为 False,则返回相同的信息作为(symbols_to_declare, not_supported_functions, code_text)的元组。[默认=True]。

contract: bool, 可选

如果为 True,则假设Indexed实例遵循张量收缩规则,并生成相应的索引嵌套循环。设置 contract=False 将不会生成循环,而是由用户负责在代码中为索引提供值。[默认=True]。

inline: bool, 可选

如果为 True,则尝试创建单语句代码而不是多语句。[默认=True]。

示例

>>> from sympy import octave_code, symbols, sin, pi
>>> x = symbols('x')
>>> octave_code(sin(x).series(x).removeO())
'x.⁵/120 - x.³/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 中编写“向量化”代码非常常见。如果值是标量,则无害。

>>> 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³' 

此类使用几个规则来决定使用哪个符号来表示乘积。纯数字使用“”,符号使用“.”,MatrixSymbols 使用“”。HadamardProduct 可用于指定两个 MatrixSymbols 的逐分量乘法“.”。目前还没有简单的方法来指定标量符号,因此有时代码可能会有些轻微的外观问题。例如,假设 x 和 y 是标量,A 是矩阵,那么虽然人类程序员可能会写成“(x²y)A³”,我们生成的代码是:

>>> octave_code(x**2*y*A**3)
'(x.².*y)*A³' 

使用 Octave 内联表示法支持矩阵。在使用assign_to与矩阵时,可以将名称指定为字符串或MatrixSymbol。在后一种情况下,维度必须对齐。

>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([[x**2, sin(x), ceiling(x)]])
>>> octave_code(mat, assign_to='A')
'A = [x.² 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.² ((x > 0).*(x + 1) + (~(x > 0)).*(x)) sin(x)];' 

通过向user_functions关键字参数传递{“type”:“function”}字典可以为特定类型定义自定义打印。或者,字典值可以是元组列表,即[(argument_test, cfunction_string)]。这可以用于调用自定义 Octave 函数。

>>> 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));' 
```  ## Rust 代码打印

```py
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={})

一个打印器,将 SymPy 表达式转换为 Rust 代码的字符串

printmethod: str = '_rust_code'
indent_code(code)

接受代码字符串或代码行列表。

sympy.printing.rust.rust_code(expr, assign_to=None, **settings)

将表达式转换为 Rust 代码字符串

参数:

expr:Expr

要转换的 SymPy 表达式。

assign_to:可选

在提供时,该参数用作分配给表达式的变量的名称。可以是字符串、SymbolMatrixSymbolIndexed类型。这在换行或生成多行语句的表达式的情况下很有帮助。

precision:整数,可选

诸如 pi 的数字精度 [默认=15]。

user_functions:字典,可选

一个字典,其中键是FunctionClassUndefinedFunction实例的字符串表示,值是它们期望的 C 字符串表示。或者,字典值可以是元组列表,即[(argument_test, cfunction_string)]。有关示例,请参见下文。

dereference:可迭代对象,可选

应在打印的代码表达式中取消引用的符号的可迭代对象。这些值通过地址传递给函数。例如,如果dereference=[a],生成的代码将打印(*a)而不是a

人类:布尔值,可选

如果为 True,则结果是一个可能包含一些常量声明的单个字符串,用于数字符号。如果为 False,则相同的信息以元组形式返回(symbols_to_declare, not_supported_functions, code_text)。[默认=True]。

合同:布尔值,可选

如果为 True,假定Indexed实例遵守张量收缩规则,并生成相应的索引的嵌套循环。设置contract=False将不生成循环,而是用户负责为代码中的索引提供值。[默认=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();' 

通过向user_functions关键字参数传递{“type”:“function”}字典可以为特定类型定义简单的自定义打印。或者,字典值可以是元组列表,即[(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]);' 

矩阵也受支持,但必须为assign_to提供相同维度的MatrixSymbol。注意,任何正常生成的表达式也可以存在于矩阵内部:

>>> 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 代码打印

```py
class sympy.printing.aesaracode.AesaraPrinter(*args, **kwargs)

创建 Aesara 符号表达式图的代码打印机。

参数:

cache : 字典

要使用的缓存字典。如果为 None(默认),将使用全局缓存。要创建不依赖或不改变全局状态的打印机,请传递一个空字典。注意:该字典在打印机初始化时不会被复制,并且将被原地更新,因此在创建多个打印机或多次调用aesara_code()aesara_function()时,缓存在所有这些应用程序之间共享。

属性

cache (dict) 一个 Aesara 变量的缓存,已为 SymPy 符号样式对象(例如sympy.core.symbol.Symbolsympy.matrices.expressions.MatrixSymbol)创建。这用于确保在表达式(或多个表达式)中对给定符号的所有引用都打印为相同的 Aesara 变量,该变量仅创建一次。符号仅通过名称和类型来区分。缓存内容的格式应视为对用户不透明。
printmethod: str = '_aesara'
doprint(expr, dtypes=None, broadcastables=None)

将 SymPy 表达式转换为 Aesara 图形变量。

dtypesbroadcastables 参数用于指定与expr中自由符号对应的 Aesara 变量的数据类型、维度和广播行为。每个都是从 SymPy 符号到aesara.tensor.var.TensorVariable相应参数的值的映射。

参见对应的文档页面,了解更多关于 Aesara 中广播的信息。

参数:

expr : sympy.core.expr.Expr

要打印的 SymPy 表达式。

dtypes : 字典

从 SymPy 符号到在创建与这些符号对应的新 Aesara 变量时使用的 Aesara 数据类型的映射。对应于aesara.tensor.var.TensorVariabledtype参数。对于未包含在映射中的符号,默认为'floatX'

broadcastables : 字典

从 SymPy 符号到aesara.tensor.var.TensorVariable创建 Aesara 变量时使用的broadcastable参数值的映射。对于未包含在映射中的符号,默认为空元组(结果为标量)。

返回:

aesara.graph.basic.Variable

表达式在 Aesara 符号表达式图中的值对应的变量。

sympy.printing.aesaracode.aesara_code(expr, cache=None, **kwargs)

将 SymPy 表达式转换为 Aesara 图变量。

参数:

expr:sympy.core.expr.Expr

要转换的 SymPy 表达式对象。

cache:字典

缓存的 Aesara 变量(参见 AesaraPrinter.cache)。默认为模块级全局缓存。

dtypes:字典

传递给 AesaraPrinter.doprint()

broadcastables:字典

传递给 AesaraPrinter.doprint()

返回:

aesara.graph.basic.Variable

表达式在 Aesara 符号表达式图中的值对应的变量。

sympy.printing.aesaracode.aesara_function(inputs, outputs, scalar=False, *, dim=None, dims=None, broadcastables=None, **kwargs)

从 SymPy 表达式创建一个 Aesara 函数。

输入和输出使用 aesara_code() 转换为 Aesara 变量,然后传递给 aesara.function

参数:

inputs

构成函数输入的符号序列。

outputs

函数输出的表达式序列。每个表达式的自由符号必须是 inputs 的子集。

scalar:布尔值

将输出中的零维数组转换为标量。这将返回一个围绕 Aesara 函数对象的 Python 封装函数。

cache:字典

缓存的 Aesara 变量(参见 AesaraPrinter.cache)。默认为模块级全局缓存。

dtypes:字典

传递给 AesaraPrinter.doprint()

broadcastables:字典

传递给 AesaraPrinter.doprint()

dims:字典

broadcastables 参数的替代方法。从 inputs 元素到指示其关联的数组/张量维数的整数的映射。如果给定,会覆盖 broadcastables 参数。

dim:整数

broadcastables 参数的另一种替代方法。用于所有数组/张量的常见维数数量。aesara_function([x, y], [...], dim=2) 等同于使用 broadcastables={x: (False, False), y: (False, False)}

返回:

可调用对象

一个可调用对象,它以 inputs 的值作为位置参数,并为 outputs 中的每个表达式返回一个输出数组。 如果 outputs 是单个表达式,则函数将返回一个 Numpy 数组;如果是多个表达式的列表,则函数将返回一个数组列表。 请参阅上面关于 squeeze 参数行为的描述。 返回的对象将是 aesara.compile.function.types.Function 的实例或其周围的 Python 包装函数。 在两种情况下,返回的值将具有指向 aesara.function 返回值的 aesara_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] 

另请参阅

dim_handling

sympy.printing.aesaracode.dim_handling(inputs, dim=None, dims=None, broadcastables=None)

从关键字参数到 aesara_function()aesara_code() 函数获取 broadcastables 参数的值。

用于向后兼容性。

参数:

inputs

输入符号的序列。

dim : 整数

所有输入的常见维数。 如果给定,则覆盖其他参数。

dims : 字典

将输入符号映射到维数的数量。 如果给定,则覆盖 broadcastables 参数。

broadcastables : 字典

明确 broadcastables 参数的值为 AesaraPrinter.doprint() 的参数。 如果不为 None,则函数将以此值不变返回。

返回:

字典

字典将 inputs 的元素映射到它们的“广播”值(bool 元组)。 ## Gtk

您可以使用位于 sympy.printing.gtk 中的 print_gtk 函数将内容打印到 gtkmathview 小部件(某些系统中需要安装 gtkmathview 和 libgtkmathview-bin)。

GtkMathView 接受 MathML,因此此渲染取决于表达式的 MathML 表示。

用法:

from sympy import *
print_gtk(x**2 + 2*exp(x**3)) 
sympy.printing.gtk.print_gtk(x, start_viewer=True)

打印到 Gtkmathview,一个能够呈现 MathML 的 gtk 小部件。

需要 libgtkmathview-bin ## LambdaPrinter

此类实现将表达式打印为可以由 sympy.utilities.lambdify.lambdify() 函数使用的字符串。

class sympy.printing.lambdarepr.LambdaPrinter(settings=None)

此打印机将表达式转换为可以由 lambdify 使用的字符串。

printmethod: str = '_lambdacode'
sympy.printing.lambdarepr.lambdarepr(expr, **settings)

返回一个可用于 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']

内置可变序列。

如果未给出参数,则构造函数将创建一个新的空列表。 如果指定,参数必须是可迭代的。

class sympy.printing.latex.LatexPrinter(settings=None)
printmethod: str = '_latex'
parenthesize_super(s)

保护上标位于 s

如果设置了 parenthesize_super 选项,则用括号保护;否则用大括号包裹。

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: 布尔值,可选

如果设置为 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 : 字符串,可选

显示反三角函数的方式。可以是'abbreviated''full''power'之一。默认为'abbreviated'

itex : 布尔值,可选

指定是否使用 itex 特定的语法,包括发射$$...$$

ln_notation : 布尔值,可选

如果设置为True,则使用\ln替代默认的\log

long_frac_ratio : 浮点数或 None,可选

分子宽度与分母宽度之比在打印机截断长分数之前的允许比例。如果为None(默认值),则不会分割长分数。

mat_delim : 字符串,可选

用于包围矩阵的定界符。可以是'[''('或空字符串''。默认为'['

mat_str : 字符串,可选

发出哪种矩阵环境字符串。对于行内模式,默认为'smallmatrix',对于最多 10 列的矩阵,默认为'matrix',否则默认为'array'

mode: 字符串,可选

指定生成的代码如何定界。mode可以是'plain''inline''equation''equation*'之一。如果将mode设置为'plain',则生成的代码将不被定界(这是默认值)。如果将mode设置为'inline',则使用行内 LaTeX $...$。如果将mode设置为'equation''equation*',则生成的代码将被包裹在equationequation*环境中(记得导入amsmath以使用equation*)。在后一种情况下,将使用$$...$$语法。

mul_symbol : 字符串或 None,可选

用于乘法的符号。可以是None'ldot''dot''times'之一。

order: 字符串,可选

支持的任意单项式顺序(当前为'lex''grlex''grevlex')、'old''none'之一。此参数对于~.Mul对象无效。将顺序设置为'old'将使用打印机中定义的~.Add的兼容顺序。对于非常大的表达式,如果速度是问题,则将order关键字设置为'none'

symbol_names : 可选,映射到符号的字符串字典

符号字典及其自定义输出字符串。

root_notation : 布尔值,可选

如果设置为False,则形如 1/n 的指数以分数形式打印。默认为True,以根式形式打印指数。

mat_symbol_style : string, optional

可以是 'plain'(默认)或 'bold'。如果设置为 'bold',则 (~.MatrixSymbol) A 将打印为 \mathbf{A},否则为 A

imaginary_unit : string, optional

用于虚数单位的字符串。定义的选项是 'i'(默认)和 'j'。在前面添加 rt,会得到 \mathrm\text,因此 'ri' 将得到 \mathrm{i},这将给出 (\mathrm{i})。

gothic_re_im : boolean, optional

如果设置为 True,则对于 reim 使用 (\Re) 和 (\Im),默认值为 False,导致对于 (\operatorname{re}) 和 (\operatorname{im})。

decimal_separator : string, optional

指定浮点数的整数部分和小数部分之间的分隔符,例如默认情况下为 period(英文句点),或者当指定为 comma 时为 2{,}5。当选择 comma 时,列表、集合和元组的元素之间以分号分隔。例如,选择 comma 后,[1; 2; 3],选择 period 后,[1,2,3]。

parenthesize_super : boolean, optional

如果设置为 False,则在求幂时不会给表达式加括号。默认为 True,在求幂时加括号。

min: Integer or None, optional

设置以固定点格式打印浮点数时指数的下限。

max: Integer or None, optional

设置以固定点格式打印浮点数时指数的上限。

diff_operator: string, optional

用于微分运算符的字符串。默认为 'd',以斜体形式打印。'rd''td'\mathrm{d}\text{d} 的快捷方式。

adjoint_style: string, optional

用于伴随符号的字符串。定义的选项是 'dagger'(默认),’star’```py, and 'hermitian'```。

注:

由于这是 Python 在字符串中转义反斜杠的方式,因此在打印时不使用 print 语句会导致 latex 命令的双反斜杠。

>>> 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}} 

modeitex 选项:

>>> 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() 还支持内置的容器类型 listtupledict

>>> 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。

sympy.printing.latex.print_latex(expr, **settings)

打印给定表达式的 LaTeX 表示。使用与 latex() 相同的设置。## MathMLPrinter

该类负责 MathML 打印。参见 sympy.printing.mathml

关于 mathml 的更多信息:www.w3.org/TR/MathML2

class sympy.printing.mathml.MathMLPrinterBase(settings=None)

包含用于 MathMLContentPrinter 和 MathMLPresentationPrinter 所需的常见代码。

doprint(expr)

将表达式打印为 MathML。

class sympy.printing.mathml.MathMLContentPrinter(settings=None)

将表达式打印为 Content MathML 标记语言的标记。

参考资料:www.w3.org/TR/MathML2/chapter4.html

printmethod: str = '_mathml_content'
mathml_tag(e)

返回表达式的 MathML 标签。

class sympy.printing.mathml.MathMLPresentationPrinter(settings=None)

将表达式打印到 Presentation MathML 标记语言中。

参考资料:www.w3.org/TR/MathML2/chapter3.html

printmethod: str = '_mathml_presentation'
mathml_tag(e)

返回表达式的 MathML 标签。

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='&#xB7;')

返回表达式的 MathML 表示。如果打印机是 presentation,则打印 Presentation MathML,否则打印 content MathML。

sympy.printing.mathml.print_mathml(expr, printer='content', **settings)

打印表达式的 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 代码打印机

该模块包含适用于纯 Python 以及启用了 NumPy 和 SciPy 的代码的 Python 代码打印机。

```py
class sympy.printing.pycode.MpmathPrinter(settings=None)

mpmath 的 Lambda 打印机,为浮点数保持精度

sympy.printing.pycode.pycode(expr, **settings)

将表达式转换为 Python 代码的字符串

参数:

expr :表达式

SymPy 表达式。

fully_qualified_modules :布尔型

是否写出函数的完整模块名称 (math.sin vs. sin). 默认值:True

standard :str 或 None,可选

仅支持 'python3'(默认)。此参数将来可能会被移除。

示例

>>> from sympy import pycode, tan, Symbol
>>> pycode(tan(Symbol('x')) + 1)
'math.tan(x) + 1' 
```  ## PythonPrinter

此类实现 Python 打印。用法:

```py
>>> 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()` 提供比 `repr()` 更低级的文本输出

示例:

```py
>>> 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() 给出 repr 形式,这是 SymPy 中通常给出的 repr(),但我们实际上不使用 srepr() 来进行 __repr__,因为它太冗长,不太可能默认调用它。另一个原因是列表调用其元素的 repr,例如 print([a, b, c]) 调用 repr(a)repr(b)repr(c)。因此,如果我们将 srepr 用于 __repr__,任何包含 SymPy 对象的列表都将包含 srepr 形式,即使我们使用 str()print()

class sympy.printing.repr.ReprPrinter(settings=None)
printmethod: str = '_sympyrepr'
emptyPrinter(expr)

回退打印机。

reprify(args, sep)

打印每个 (args) 中的项,并使用 (sep) 连接它们。

sympy.printing.repr.srepr(expr, *, order=None, perm_cyclic=True)

以 repr 形式返回表达式 ## StrPrinter

此模块生成 SymPy 表达式的可读表示。

class sympy.printing.str.StrPrinter(settings=None)
printmethod: str = '_sympystr'
sympy.printing.str.sstr(expr, *, order=None, full_prec='auto', sympy_integers=False, abbrev=False, perm_cyclic=True, min=None, max=None)

返回表达式的字符串。

对于需要速度的大型表达式,使用设置 order='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 形式返回表达式

即,字符串以引号形式返回,其他所有内容均以字符串形式返回。

此函数可能对接入 sys.displayhook ## 树形打印 有用

此模块中的函数创建表达式的树形表示。

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)

返回有关“node”的信息。

包括类名、字符串表示和假设。

参数:

assumptions :布尔型,可选

查看 tree 中的 assumptions 关键字

sympy.printing.tree.tree(node, assumptions=True)

将“node”的树形表示作为字符串返回。

它在节点.args 上递归地使用 print_node() 和 pprint_nodes()。

参数:

asssumptions : bool, optional

标志用于决定是否打印与表达式关联的所有假设数据(例如 pyis_integer`, ``is_real)。

启用标志会使结果冗长,并且由于在回溯假设时使用的随机性,打印结果可能不确定。

另请参阅

print_tree

sympy.printing.tree.print_tree(node, assumptions=True)

打印 “node” 的树形表示。

参数:

asssumptions : bool, optional

标志决定是否打印与表达式关联的所有假设数据(例如 pyis_integer`, ``is_real)。

启用标志会使结果冗长,并且由于在回溯假设时使用的随机性,打印结果可能不确定。

示例

>>> 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 

另请参阅

tree

预览

一个有用的函数是 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)

查看表达式或 LaTeX 标记以 PNG、DVI、PostScript 或 PDF 形式。

如果表达式参数是一个表达式,则将其导出到 LaTeX,然后使用可用的 TeX 发行版进行编译。第一个参数 ‘expr’ 也可以是 LaTeX 字符串。然后函数将运行给定输出格式的适当查看器或使用用户定义的查看器。默认生成 png 输出。

默认情况下,用于排版的漂亮 Euler 字体(用于排版著名的 “Concrete Mathematics” 书籍)。为此工作,您需要 ‘eulervm.sty’ LaTeX 样式(在 Debian/Ubuntu 中,安装 texlive-fonts-extra 包)。如果您更喜欢默认的 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') 

然后 ‘view’ 将在您的系统上查找可用的 ‘dvi’ 查看器(在函数中预定义,因此首先尝试 evince,然后是 kdvi 和 xdvi)。如果找不到任何内容,它将退回到使用系统文件关联(通过 openxdg-open)。要始终使用您的系统文件关联而不搜索上述读取器,请使用

>>> from sympy.printing.preview import system_default_viewer
>>> preview(x + y, output='dvi', viewer=system_default_viewer) 

如果这仍然找不到您想要的查看器,可以显式设置。

>>> preview(x + y, output='dvi', viewer='superior-dvi-viewer') 

这将跳过自动检测,并运行用户指定的 ‘superior-dvi-viewer’。如果 view 在您的系统上找不到它,它将优雅地引发异常。

您也可以输入 'file' 作为查看器参数。这样做将导致此函数以只读模式返回一个文件对象,如果未设置 filename。但是,如果设置了,那么 ‘preview’ 将生成的文件写入此文件名。

还支持写入类似 io.BytesIO 的对象,需要传递给 outputbuffer 参数。

>>> 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) 

还可以使用标准导言,并使用 extra_preamble 关键字参数提供额外的信息。

>>> from sympy import sin
>>> extra_preamble = "\\renewcommand{\\sin}{\\cos}"
>>> preview(sin(x), output='png', extra_preamble=extra_preamble) 

如果‘output’的值与‘dvi’不同,则可以为‘dvi’+输出转换工具的执行设置命令行选项(‘dvioptions’参数)。这些选项必须以字符串列表的形式给出(参见 subprocess.Popen)。

附加关键字参数将传递给 latex() 调用,例如 symbol_names 标志。

>>> phidd = Symbol('phidd')
>>> preview(phidd, symbol_names={phidd: r'\ddot{\varphi}'}) 

通过将所需的文件名传递给 ‘outputTexFile’ 关键字参数,可以将生成的 TeX 文件写入文件。要将 TeX 代码写入名为 "sample.tex" 的文件,并运行默认的 png 查看器以显示生成的位图,请执行以下操作

>>> preview(x + y, outputTexFile="sample.tex") 

实现 - 辅助类/函数

sympy.printing.conventions.split_super_sub(text)

将符号名称拆分为名称、上标和下标。

符号名称的第一部分被视为其实际“名称”,后跟上标和下标。每个上标前面带有“^”字符或“__”。每个下标前面带有“_”字符。三个返回值分别是实际名称、包含上标的列表和包含下标的列表。

示例

>>> from sympy.printing.conventions import split_super_sub
>>> split_super_sub('a_x¹')
('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)

将表达式打印为代码。

参数:

expr:表达式

要打印的表达式。

assign_to:符号、字符串、MatrixSymbol、字符串列表或符号(可选)

如果提供了,打印的代码将把表达式设置为在 assign_to 中给定的变量或多个变量的名称。

exception sympy.printing.codeprinter.AssignmentError

如果缺少循环的分配变量,则引发异常。### 优先级

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.precedence.precedence(item)

返回给定对象的优先级。

这是 StrPrinter 的优先级。## 漂亮打印实现辅助函数

sympy.printing.pretty.pretty_symbology.U(name)

通过名称获取 Unicode 字符,如果找不到则返回 None

这是因为较旧版本的 Python 使用较旧的 Unicode 数据库。

sympy.printing.pretty.pretty_symbology.pretty_use_unicode(flag=None)

设置漂亮打印机默认是否使用 Unicode。

sympy.printing.pretty.pretty_symbology.pretty_try_use_unicode()

查看是否可以使用 Unicode 输出,并在可能时利用它。

sympy.printing.pretty.pretty_symbology.xstr(*args)

以下两个函数返回输入的希腊字母的 Unicode 版本。

sympy.printing.pretty.pretty_symbology.g(l)
sympy.printing.pretty.pretty_symbology.G(l)
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']

内置可变序列。

如果未给出参数,则构造函数创建一个新的空列表。如果指定了参数,必须是可迭代的。

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.xobj(symb, length)

构造给定长度的空间对象。

返回:[],长度相等的字符串。

sympy.printing.pretty.pretty_symbology.vobj(symb, height)

构建给定高度的垂直对象。

见:xobj

sympy.printing.pretty.pretty_symbology.hobj(symb, width)

构建给定宽度的水平对象。

见:xobj

以下常数用于呈现根和分数。

sympy.printing.pretty.pretty_symbology.root = {2: '√', 3: '∛', 4: '∜'}
sympy.printing.pretty.pretty_symbology.VF(txt)
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.xsym(sym)

获取‘character’的符号学。

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.pretty_symbol(symb_name, bold_name=False)

返回符号的漂亮表示。

sympy.printing.pretty.pretty_symbology.annotated(letter)

返回字母letter的风格化图,以及如何在其上方和下方放置标注(上标和下标)的信息。

请查看 pretty.py 函数 _print_meijerg,_print_hyper,了解如何使用此信息。

由 Jurjen Bos 编写的 Prettyprinter。(我讨厌垃圾邮件:请发邮件至 ku.oc.oohay 的反向地址)。所有对象都有一个创建“stringPict”的方法,可在用于漂亮打印的 str 方法中使用。

由 Jason Gedge 更新(电子邮件<我的姓氏> at cs mun ca)

  • terminal_string() 方法

  • 小修复和更改(主要是对 prettyForm 的修复)

待办事项:

  • 允许对上方/下方进行左/居中/右对齐选项,并对左侧/右侧进行上/居中/下对齐选项。
class sympy.printing.pretty.stringpict.stringPict(s, baseline=0)

ASCII 图片。图片表示为等长字符串列表。

above(*args)

将图片放在此图片上方。返回字符串,用于 stringPict 的基线参数。基线是底部图片的基线。

below(*args)

将图片放在此图片下方。返回字符串,用于 stringPict 的基线参数。基线是顶部图片的基线。

示例

>>> from sympy.printing.pretty.stringpict import stringPict
>>> print(stringPict("x+3").below(
...       stringPict.LINE, '3')[0]) 
x+3
---
 3 
height()

图片在字符中的高度。

left(*args)

将图片(从左到右)放在左边。返回字符串,用于 stringPict 的基线参数。

leftslash()

在对象前加上适当大小的斜杠。

static next(*args)

将一串 stringPicts 放在一起。返回字符串,用于 stringPict 的基线参数。

parens(left='(', right=')', ifascii_nougly=False)

将自身放在括号中。返回字符串,用于 stringPict 的基线参数。

左侧或右侧可以是 None 或空字符串,表示“该侧没有括号”。

render(*args, **kwargs)

返回自身的字符串形式。

除非设置参数line_break为 False,否则将在可以在终端上打印的形式中断表达式,而不会中断它。

right(*args)

将图片放在这个旁边。返回字符串,用于 stringPict 的基线参数。(多行)字符串被允许,并且给出基线为 0。

示例

>>> from sympy.printing.pretty.stringpict import stringPict
>>> print(stringPict("10").right(" + ",stringPict("1\r-\r2",1))[0])
 1
10 + -
 2 
root(n=None)

生成一个漂亮的根符号。对大 n 插入产生丑陋的结果。

static stack(*args)

将图片从上到下放在一起。返回字符串,用于 stringPict 的基线参数。基线是第二张图片的基线。一切都居中。基线是第二张图片的基线。允许字符串。特殊值 stringPict.LINE 是一排‘-’扩展到宽度。

terminal_width()

如果可能,返回终端宽度,否则返回 0。

width()

图片在字符中的宽度。

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) 
static apply(function, *args)

一个或多个变量的函数。

dotprint

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 表达式树的 DOT 描述

参数:

styles:由(类,映射)组成的列表的列表,可选

不同类别的样式。

默认值是

(

    (Basic, {'color': 'blue', 'shape': 'ellipse'}),

    (Expr,  {'color': 'black'})

) 

atom:函数,可选

用于确定参数是否为原子的函数。

一个好的选择是lambda x: not x.args

默认值是lambda x: not isinstance(x, Basic)

maxdepth:整数,可选

最大深度。

默认值为None,表示没有限制。

repeat:布尔值,可选

是否对常见子表达式使用不同节点。

默认值为True

例如,对于带有repeat=Truex + x*y,将会有两个x的节点;而对于repeat=False,将只有一个节点。

警告

即使像Pow(x, x)中的x在同一对象中出现两次,它仍然只会出现一次。因此,对于repeat=False,对象的箭头数量可能不等于其参数数量。

labelfunc:函数,可选

为给定叶节点创建标签的函数。

默认值为str

另一个好选择是srepr

例如,使用str时,x + 1的叶节点标记为x1。使用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,)";
} 

主题

原文链接:docs.sympy.org/latest/reference/public/topics/index.html

目录

  • 几何学

    • 实体

    • 实用工具

    • 线

    • 曲线

    • 椭圆

    • 多边形

    • 平面

  • 全息函数

    • 关于全息函数

    • SymPy 中全息函数的表示

    • 全息函数操作

    • 将其他表示形式转换为全息函数

    • 用途与当前限制

    • 内部 API

  • 李代数

  • 多项式操作

    • 模块的基本功能

    • Wester 文章中的例子

    • 多项式操作模块参考

    • AGCA - 代数几何与交换代数模块

    • 多项式模块的域介绍

    • Poly Domains 的参考文档

    • 多项式操作模块的内部

    • 使用多项式进行级数操作

    • 文献资料

    • 多项式求解器

    • 多项式模块的域矩阵介绍

    • 数域

  • 范畴论

  • 密码学

  • 微分几何

  • 绘图

  • 统计

几何

原文:docs.sympy.org/latest/modules/geometry/index.html

简介

SymPy 的几何模块允许创建二维几何实体,如直线和圆,并查询有关这些实体的信息。这可能包括询问椭圆的面积,检查一组点的共线性,或找到两条线的交点。该模块的主要用例涉及具有数值值的实体,但也可以使用符号表示。

可用实体

当前在几何模块中可用的实体包括:

  • 线, 线段, 射线

  • 椭圆,

  • 多边形, 正多边形, 三角形

大部分工作都将通过这些实体的属性和方法完成,但也存在一些全局方法:

  • intersection(entity1, entity2)

  • are_similar(entity1, entity2)

  • convex_hull(points)

有关完整的 API 列表及其方法和返回值的解释,请参阅本文档末尾的类列表。

示例用法

以下 Python 会话给出了如何使用几何模块的一些想法。

>>> from sympy import *
>>> from sympy.geometry import *
>>> x = Point(0, 0)
>>> y = Point(1, 1)
>>> z = Point(2, 2)
>>> zp = Point(1, 0)
>>> Point.is_collinear(x, y, z)
True
>>> Point.is_collinear(x, y, zp)
False
>>> t = Triangle(zp, y, x)
>>> t.area
1/2
>>> t.medians[x]
Segment2D(Point2D(0, 0), Point2D(1, 1/2))
>>> m = t.medians
>>> intersection(m[x], m[y], m[zp])
[Point2D(2/3, 1/3)]
>>> c = Circle(x, 5)
>>> l = Line(Point(5, -5), Point(5, 5))
>>> c.is_tangent(l) # is l tangent to c?
True
>>> l = Line(x, y)
>>> c.is_tangent(l) # is l tangent to c?
False
>>> intersection(c, l)
[Point2D(-5*sqrt(2)/2, -5*sqrt(2)/2), Point2D(5*sqrt(2)/2, 5*sqrt(2)/2)] 

中位线的交点

>>> from sympy import symbols
>>> from sympy.geometry import Point, Triangle, intersection

>>> a, b = symbols("a,b", positive=True)

>>> x = Point(0, 0)
>>> y = Point(a, 0)
>>> z = Point(2*a, b)
>>> t = Triangle(x, y, z)

>>> t.area
a*b/2

>>> t.medians[x]
Segment2D(Point2D(0, 0), Point2D(3*a/2, b/2))

>>> intersection(t.medians[x], t.medians[y], t.medians[z])
[Point2D(a, b/3)] 

一个深入例子:帕普斯的六边形定理

来自维基百科(维基帕普斯):

给定一组共线点 (A), (B), (C), 和另一组共线点 (a), (b), (c), 则线对 (Ab) 和 (aB), (Ac) 和 (aC), (Bc) 和 (bC) 的交点 (X), (Y), (Z) 是共线的。

>>> from sympy import *
>>> from sympy.geometry import *
>>>
>>> l1 = Line(Point(0, 0), Point(5, 6))
>>> l2 = Line(Point(0, 0), Point(2, -2))
>>>
>>> def subs_point(l, val):
...  """Take an arbitrary point and make it a fixed point."""
...    t = Symbol('t', real=True)
...    ap = l.arbitrary_point()
...    return Point(ap.x.subs(t, val), ap.y.subs(t, val))
...
>>> p11 = subs_point(l1, 5)
>>> p12 = subs_point(l1, 6)
>>> p13 = subs_point(l1, 11)
>>>
>>> p21 = subs_point(l2, -1)
>>> p22 = subs_point(l2, 2)
>>> p23 = subs_point(l2, 13)
>>>
>>> ll1 = Line(p11, p22)
>>> ll2 = Line(p11, p23)
>>> ll3 = Line(p12, p21)
>>> ll4 = Line(p12, p23)
>>> ll5 = Line(p13, p21)
>>> ll6 = Line(p13, p22)
>>>
>>> pp1 = intersection(ll1, ll3)[0]
>>> pp2 = intersection(ll2, ll5)[0]
>>> pp3 = intersection(ll4, ll6)[0]
>>>
>>> Point.is_collinear(pp1, pp2, pp3)
True 

参考文献

[维基帕普斯]

“帕普斯的六边形定理” 维基百科,自由百科全书。网络。2013 年 4 月 26 日。 <zh.wikipedia.org/wiki/%E6%B3%A2%E5%B8%95%E6%96%AF>

杂注

  • PolygonTriangle 的面积属性可能返回正值或负值,这取决于点的顺时针或逆时针方向。如果您总是希望得到正值,请确保使用 abs 函数。

  • 虽然多边形可以指任何类型的多边形,但代码是为简单多边形编写的。因此,如果处理复杂多边形(重叠边),请预期可能出现问题。

  • 因为 SymPy 还处于初期阶段,某些情况可能无法正确简化,因此一些应返回True的情况(例如Point.is_collinear)实际上可能不会返回。类似地,试图找到相交的实体的交点可能会导致空结果。

未来的工作

真值设置表达式

当处理符号实体时,经常会出现无法保证断言的情况。例如,考虑以下代码:

>>> from sympy import *
>>> from sympy.geometry import *
>>> x,y,z = map(Symbol, 'xyz')
>>> p1,p2,p3 = Point(x, y), Point(y, z), Point(2*x*y, y)
>>> Point.is_collinear(p1, p2, p3)
False 

即使结果目前是False,这并不总是真的。如果数量 (z - y - 2yz + 2*y**2 == 0),那么这些点将共线。告知用户这一点将非常有用,因为这样的数量可能对用户进行进一步的计算有用,至少知道这一点也是很好的。可以通过返回一个对象(例如,GeometryResult)来实现这一点,用户可以使用这个对象。实际上,这不需要大量的工作。

三维及以上

目前几何模块的有限子集已扩展到三维,但显然扩展更多将是一个很好的补充。这可能涉及相当多的工作,因为许多使用的算法是特定于二维的。

几何可视化

绘图模块能够绘制几何实体。在绘图模块条目中查看绘制几何实体。

子模块

  • 实体

  • 实用工具

  • 直线

  • 曲线

  • 椭圆

  • 多边形

  • 平面

实体

原始文档:docs.sympy.org/latest/modules/geometry/entities.html

class sympy.geometry.entity.GeometryEntity(*args, **kwargs)

所有几何实体的基类。

此类不代表任何特定几何实体,仅提供所有子类常见方法的实现。

property ambient_dimension

对象所包含的空间的维数是多少?

property bounds

返回表示几何图形边界的矩形 (xmin, ymin, xmax, ymax) 元组。

encloses(o)

如果o位于self的边界内部(而不是在边界上或外部),则返回True

将对象分解为点和单独的实体,只需为其类定义一个encloses_point方法。

示例

>>> from sympy import RegularPolygon, Point, Polygon
>>> t  = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
>>> t2 = Polygon(*RegularPolygon(Point(0, 0), 2, 3).vertices)
>>> t2.encloses(t)
True
>>> t.encloses(t2)
False 

另请参阅

sympy.geometry.ellipse.Ellipse.encloses_point, sympy.geometry.polygon.Polygon.encloses_point

intersection(o)

返回与自身相交的所有交点列表。

注意

实体不需要实现此方法。

如果两种不同类型的实体可以相交,则在ordering_of_classes中索引较高的项目应实现与索引较低的任何项目的相交。

另请参阅

sympy.geometry.util.intersection

is_similar(other)

此几何实体是否与另一几何实体相似?

如果可以通过统一缩放(放大或缩小)其中一个实体来获得另一个实体,则两个实体是相似的。

注意

此方法不打算直接使用,而是通过util.py中的are_similar函数。实体不需要实现此方法。如果两种不同类型的实体可以相似,则只需要其中一种能够确定这一点。

另请参阅

scale

parameter_value(other, t)

返回与给定点对应的参数。在此参数值处评估实体的任意点将返回给定点。

示例

>>> from sympy import Line, Point
>>> from sympy.abc import t
>>> a = Point(0, 0)
>>> b = Point(2, 2)
>>> Line(a, b).parameter_value((1, 1), t)
{t: 1/2}
>>> Line(a, b).arbitrary_point(t).subs(_)
Point2D(1, 1) 
reflect(line)

将对象沿线进行反射。

参数:

线:线

示例

>>> from sympy import pi, sqrt, Line, RegularPolygon
>>> l = Line((0, pi), slope=sqrt(2))
>>> pent = RegularPolygon((1, 2), 1, 5)
>>> rpent = pent.reflect(l)
>>> rpent
RegularPolygon(Point2D(-2*sqrt(2)*pi/3 - 1/3 + 4*sqrt(2)/3, 2/3 + 2*sqrt(2)/3 + 2*pi/3), -1, 5, -atan(2*sqrt(2)) + 3*pi/5) 
>>> from sympy import pi, Line, Circle, Point
>>> l = Line((0, pi), slope=1)
>>> circ = Circle(Point(0, 0), 5)
>>> rcirc = circ.reflect(l)
>>> rcirc
Circle(Point2D(-pi, pi), -5) 
rotate(angle, pt=None)

以逆时针绕点pt旋转angle弧度。

默认pt为原点,Point(0, 0)

示例

>>> from sympy import Point, RegularPolygon, Polygon, pi
>>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
>>> t # vertex on x axis
Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
>>> t.rotate(pi/2) # vertex on y axis now
Triangle(Point2D(0, 1), Point2D(-sqrt(3)/2, -1/2), Point2D(sqrt(3)/2, -1/2)) 

另请参阅

scale, translate

scale(x=1, y=1, pt=None)

通过将 x 和 y 坐标乘以 x 和 y 来缩放对象。

如果给定了pt,则按照该点进行缩放;对象被移动到-pt,进行缩放,然后再移动到pt

示例

>>> from sympy import RegularPolygon, Point, Polygon
>>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
>>> t
Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
>>> t.scale(2)
Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)/2), Point2D(-1, -sqrt(3)/2))
>>> t.scale(2, 2)
Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)), Point2D(-1, -sqrt(3))) 

另请参阅

rotate, translate

translate(x=0, y=0)

将对象移动,通过增加 x 和 y 坐标的值。

示例

>>> from sympy import RegularPolygon, Point, Polygon
>>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
>>> t
Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
>>> t.translate(2)
Triangle(Point2D(3, 0), Point2D(3/2, sqrt(3)/2), Point2D(3/2, -sqrt(3)/2))
>>> t.translate(2, 2)
Triangle(Point2D(3, 2), Point2D(3/2, sqrt(3)/2 + 2), Point2D(3/2, 2 - sqrt(3)/2)) 

另见

rotate, scale

工具

原文:docs.sympy.org/latest/modules/geometry/utils.html

sympy.geometry.util.intersection(*entities, pairwise=False, **kwargs)

几何实体集合的交集。

参数:

entities:几何实体序列

pairwise (关键字参数):可以是 True 或 False

返回:

intersection:几何实体列表

引发:

未实现错误

当无法计算交集时。

注意

任何几何实体与自身的交集应返回包含该实体的列表中的一个项目。交集需要两个或更多实体。如果只给定一个单独实体,则该函数将返回一个空列表。可能由于未完全内部简化所需量而导致(intersection)错过已知存在的交点。实数应转换为有理数,例如 Rational(str(real_num)),否则可能由于浮点数问题而失败。

情况 1:当关键字参数‘pairwise’为 False(默认值)时:在这种情况下,函数返回所有实体共有的交集列表。

情况 2:当关键字参数‘pairwise’为 True 时:在这种情况下,函数返回发生在任意一对实体之间的交集列表。

示例

>>> from sympy import Ray, Circle, intersection
>>> c = Circle((0, 1), 1)
>>> intersection(c, c.center)
[]
>>> right = Ray((0, 0), (1, 0))
>>> up = Ray((0, 0), (0, 1))
>>> intersection(c, right, up)
[Point2D(0, 0)]
>>> intersection(c, right, up, pairwise=True)
[Point2D(0, 0), Point2D(0, 2)]
>>> left = Ray((1, 0), (0, 0))
>>> intersection(right, left)
[Segment2D(Point2D(0, 0), Point2D(1, 0))] 

另请参阅

sympy.geometry.entity.GeometryEntity.intersection

sympy.geometry.util.convex_hull(*args, polygon=True)

包含在实体列表中的点所围成的凸多边形。

参数:

args:一组点、线段和/或多边形

返回:

凸包:如果polygon为 True,则为多边形,否则为一个元组((U, L)),其中

LU 分别是下凸壳和上凸壳。

可选参数

polygonBoolean。如果为 True,则返回多边形;如果为 false,则返回一个元组,如下所示。

默认值为 True。

注意

这只能在其坐标可以在数轴上排序的一组点上执行。

示例

>>> from sympy import convex_hull
>>> points = [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)]
>>> convex_hull(*points)
Polygon(Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4))
>>> convex_hull(*points, **dict(polygon=False))
([Point2D(-5, 2), Point2D(15, 4)],
 [Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4)]) 

另请参阅

sympy.geometry.point.Pointsympy.geometry.polygon.Polygon

参考文献

[R563]

zh.wikipedia.org/wiki/格雷厄姆扫描

[R564]

安德鲁单调链算法(A.M. Andrew,“另一种有效的二维凸包算法”,1979)web.archive.org/web/20210511015444/http://geomalgorithms.com/a10-_hull-1.html

sympy.geometry.util.are_similar(e1, e2)

两个几何实体是否相似。

一个几何实体能否均匀缩放到另一个几何实体?

参数:

e1:几何实体

e2:几何实体

返回:

are_similar:布尔值

引发:

几何错误

当(e1)和(e2)无法比较时。

注意

如果两个对象相等,则它们是相似的。

示例

>>> from sympy import Point, Circle, Triangle, are_similar
>>> c1, c2 = Circle(Point(0, 0), 4), Circle(Point(1, 4), 3)
>>> t1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
>>> t2 = Triangle(Point(0, 0), Point(2, 0), Point(0, 2))
>>> t3 = Triangle(Point(0, 0), Point(3, 0), Point(0, 1))
>>> are_similar(t1, t2)
True
>>> are_similar(t1, t3)
False 

另请参阅

sympy.geometry.entity.GeometryEntity.is_similar

sympy.geometry.util.centroid(*args)

寻找仅包含点、线段或多边形的集合的质心(重心)。 质心是各个质心的加权平均值,其中权重是长度(线段)或面积(多边形)。 重叠区域将增加该区域的权重。

如果没有对象(或混合对象),则返回None

示例

>>> from sympy import Point, Segment, Polygon
>>> from sympy.geometry.util import centroid
>>> p = Polygon((0, 0), (10, 0), (10, 10))
>>> q = p.translate(0, 20)
>>> p.centroid, q.centroid
(Point2D(20/3, 10/3), Point2D(20/3, 70/3))
>>> centroid(p, q)
Point2D(20/3, 40/3)
>>> p, q = Segment((0, 0), (2, 0)), Segment((0, 0), (2, 2))
>>> centroid(p, q)
Point2D(1, 2 - sqrt(2))
>>> centroid(Point(0, 0), Point(2, 0))
Point2D(1, 0) 

将 3 个多边形堆叠在一起有效地使该多边形的重量增加三倍:

>>> p = Polygon((0, 0), (1, 0), (1, 1), (0, 1))
>>> q = Polygon((1, 0), (3, 0), (3, 1), (1, 1))
>>> centroid(p, q)
Point2D(3/2, 1/2)
>>> centroid(p, p, p, q) # centroid x-coord shifts left
Point2D(11/10, 1/2) 

将正方形垂直堆叠在p的上方和下方具有相同的效果:

>>> centroid(p, p.translate(0, 1), p.translate(0, -1), q)
Point2D(11/10, 1/2) 

另请参阅

sympy.geometry.point.Point, sympy.geometry.line.Segment, sympy.geometry.polygon.Polygon

sympy.geometry.util.idiff(eq, y, x, n=1)

假设eq == 0,返回dy/dx

参数:

y:因变量或因变量列表(以y开头)

x:进行导数计算的变量

n:导数的阶数(默认为 1)

示例

>>> from sympy.abc import x, y, a
>>> from sympy.geometry.util import idiff 
>>> circ = x**2 + y**2 - 4
>>> idiff(circ, y, x)
-x/y
>>> idiff(circ, y, x, 2).simplify()
(-x**2 - y**2)/y**3 

在这里,假设ax无关:

>>> idiff(x + a + y, y, x)
-1 

现在通过在列表中将a列在y之后,使得a的 x 依赖性变得明确。

>>> idiff(x + a + y, [y, a], x)
-Derivative(a, x) - 1 

另请参阅

sympy.core.function.Derivative

表示未求值的导数

sympy.core.function.diff

显式地针对符号进行微分

原文:docs.sympy.org/latest/modules/geometry/points.html

class sympy.geometry.point.Point(*args, **kwargs)

n 维欧几里得空间中的一个点。

参数:

coords:n 个坐标值的序列。在特定

情况下,n=2 或 3,将相应创建 Point2D 或 Point3D。

evaluate:如果为 (True)(默认值),所有浮点数都会转换为

精确的类型。

dim:点应具有的坐标数。如果坐标

未指定时,它们将填充为零。

on_morph:指示当数量变化时应该发生什么

通过添加或删除零来更改点的坐标。可能的值为 ('warn'), ('error'), 或 (ignore)(默认)。当 (*args) 为空且给定 (dim) 时不发出警告或错误。尝试移除非零坐标时总是引发错误。

引发:

TypeError:当使用不是 Point 或序列的东西进行实例化时

ValueError:当使用长度小于 2 或

尝试减少维度时,如果设置了关键字 (on_morph='error'),则会引发错误。

示例

>>> from sympy import Point
>>> from sympy.abc import x
>>> Point(1, 2, 3)
Point3D(1, 2, 3)
>>> Point([1, 2])
Point2D(1, 2)
>>> Point(0, x)
Point2D(0, x)
>>> Point(dim=4)
Point(0, 0, 0, 0) 

浮点数会自动转换为 Rational,除非 evaluate 标志为 False:

>>> Point(0.5, 0.25)
Point2D(1/2, 1/4)
>>> Point(0.5, 0.25, evaluate=False)
Point2D(0.5, 0.25) 

参见

sympy.geometry.line.Segment

连接两个点

属性

长度
原点:表示适当维度空间的原点。
static affine_rank(*args)

一组点的仿射秩是包含所有点的最小仿射空间的维数。例如,如果点位于一条直线上(并且不全相同),它们的仿射秩为 1。如果点位于平面上但不是一条直线,则它们的仿射秩为 2。按照惯例,空集的仿射秩为 -1。

property ambient_dimension

此点具有的组件数量。

classmethod are_coplanar(*points)

如果存在一个平面,所有点都位于其中,则返回 True。如果 (len(points) < 3) 或所有点都是二维的,则返回一个平凡的 True 值。

参数:

一组点

返回:

布尔值

引发:

ValueError:如果给出的唯一点少于 3 个

示例

>>> from sympy import Point3D
>>> p1 = Point3D(1, 2, 2)
>>> p2 = Point3D(2, 7, 2)
>>> p3 = Point3D(0, 0, 2)
>>> p4 = Point3D(1, 1, 2)
>>> Point3D.are_coplanar(p1, p2, p3, p4)
True
>>> p5 = Point3D(0, 1, 3)
>>> Point3D.are_coplanar(p1, p2, p3, p5)
False 
canberra_distance(p)

从 self 到点 p 的 Canberra 距离。

返回到点 p 的水平和垂直距离的加权和。

参数:

p:点

返回:

canberra_distance:水平和垂直的加权和

到点 p 的距离。使用的权重是绝对值之和

坐标的

引发:

ValueError 当两个向量都为零时。

示例

>>> from sympy import Point
>>> p1, p2 = Point(1, 1), Point(3, 3)
>>> p1.canberra_distance(p2)
1
>>> p1, p2 = Point(0, 0), Point(3, 3)
>>> p1.canberra_distance(p2)
2 

参见

sympy.geometry.point.Point.distance

distance(other)

self 和另一个 GeometricEntity 之间的欧几里得距离。

返回:

distance:数字或符号表达式。

引发:

TypeError:如果其他对象不能识别为 GeometricEntity 或是

未定义距离的 GeometricEntity。

示例

>>> from sympy import Point, Line
>>> p1, p2 = Point(1, 1), Point(4, 5)
>>> l = Line((3, 1), (2, 2))
>>> p1.distance(p2)
5
>>> p1.distance(l)
sqrt(2) 

计算得到的距离也可能是符号的:

>>> from sympy.abc import x, y
>>> p3 = Point(x, y)
>>> p3.distance((0, 0))
sqrt(x**2 + y**2) 

参见

sympy.geometry.line.Segment.length, sympy.geometry.point.Point.taxicab_distance

dot(p)

返回 self 与另一个点的点积。

equals(other)

返回 self 和 other 的坐标是否一致。

intersection(other)

该点与另一个几何实体的交点。

参数:

其他 : 几何实体或坐标序列

返回:

交点 : 点列表

注释

如果没有交点则返回空列表,否则将包含该点。

示例

>>> from sympy import Point
>>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, 0)
>>> p1.intersection(p2)
[]
>>> p1.intersection(p3)
[Point2D(0, 0)] 
is_collinear(*args)

如果存在一条包含 self 和 points 的直线,则返回 True。否则返回 False。如果未给出任何点,则返回一个显然为 True 的值。

参数:

args : 点序列

返回:

共线 : 布尔值

示例

>>> from sympy import Point
>>> from sympy.abc import x
>>> p1, p2 = Point(0, 0), Point(1, 1)
>>> p3, p4, p5 = Point(2, 2), Point(x, x), Point(1, 2)
>>> Point.is_collinear(p1, p2, p3, p4)
True
>>> Point.is_collinear(p1, p2, p3, p5)
False 

另见

sympy.geometry.line.Line

is_concyclic(*args)

self 和给定的点序列是否在同一个圆内?

如果点集是共圆的则返回 True,否则返回 False。如果点数少于 2 个,则返回一个显然为 True 的值。

参数:

args : 点序列

返回:

共圆 : 布尔值

示例

>>> from sympy import Point 

定义 4 个位于单位圆上的点:

>>> p1, p2, p3, p4 = Point(1, 0), (0, 1), (-1, 0), (0, -1) 
>>> p1.is_concyclic() == p1.is_concyclic(p2, p3, p4) == True
True 

定义一个不在该圆上的点:

>>> p = Point(1, 1) 
>>> p.is_concyclic(p1, p2, p3)
False 
property is_nonzero

如果任何坐标非零,则为 True,如果每个坐标都为零,则为 False,如果无法确定,则为 None。

is_scalar_multiple(p)

返回 self 的每个坐标是否是点 p 对应坐标的标量倍。

property is_zero

如果每个坐标都为零,则为 True,如果任何坐标不为零,则为 False,如果无法确定,则为 None。

property length

将点视为线,返回点的长度为 0。

示例

>>> from sympy import Point
>>> p = Point(0, 1)
>>> p.length
0 
midpoint(p)

自身和点 p 之间的中点。

参数:

p : 点

返回:

中点 : 点

示例

>>> from sympy import Point
>>> p1, p2 = Point(1, 1), Point(13, 5)
>>> p1.midpoint(p2)
Point2D(7, 3) 

另见

sympy.geometry.line.Segment.midpoint

property origin

与当前点环境维度相同的所有零点

property orthogonal_direction

返回一个与包含 self 和原点的线垂直的非零点。

示例

>>> from sympy import Line, Point
>>> a = Point(1, 2, 3)
>>> a.orthogonal_direction
Point3D(-2, 1, 0)
>>> b = _
>>> Line(b, b.origin).is_perpendicular(Line(a, a.origin))
True 
static project(a, b)

将点 a 投影到原点和点 b 之间的线上,沿法线方向。

参数:

a : 点

b : 点

返回:

p : 点

示例

>>> from sympy import Line, Point
>>> a = Point(1, 2)
>>> b = Point(2, 5)
>>> z = a.origin
>>> p = Point.project(a, b)
>>> Line(p, a).is_perpendicular(Line(p, b))
True
>>> Point.is_collinear(z, p, b)
True 

另见

sympy.geometry.line.LinearEntity.projection

taxicab_distance(p)

self 到点 p 的曼哈顿距离。

返回到点 p 的水平和垂直距离的总和。

参数:

p : 点

返回:

曼哈顿距离 : 水平方向的总和

和到点 p 的垂直距离。

示例

>>> from sympy import Point
>>> p1, p2 = Point(1, 1), Point(4, 5)
>>> p1.taxicab_distance(p2)
7 

另见

sympy.geometry.point.Point.distance

property unit

返回与 (self) 方向相同且距原点距离为 1 的点。

class sympy.geometry.point.Point2D(*args, _nocheck=False, **kwargs)

二维欧几里得空间中的一个点。

Parameters:

坐标

两个坐标值的序列。

抛出:

类型错误

尝试添加或减去不同维度的点时。尝试创建超过两个维度的点时。调用 (intersection) 时使用的对象不是点。

示例

>>> from sympy import Point2D
>>> from sympy.abc import x
>>> Point2D(1, 2)
Point2D(1, 2)
>>> Point2D([1, 2])
Point2D(1, 2)
>>> Point2D(0, x)
Point2D(0, x) 

浮点数会自动转换为有理数,除非 evaluate 标志为 False:

>>> Point2D(0.5, 0.25)
Point2D(1/2, 1/4)
>>> Point2D(0.5, 0.25, evaluate=False)
Point2D(0.5, 0.25) 

参见

sympy.geometry.line.Segment

连接两个点。

属性

x
y
长度
property bounds

返回表示几何图形的边界矩形的元组 (xmin, ymin, xmax, ymax)。

property coordinates

返回点的两个坐标。

示例

>>> from sympy import Point2D
>>> p = Point2D(0, 1)
>>> p.coordinates
(0, 1) 
rotate(angle, pt=None)

绕点 pt 逆时针旋转 angle 弧度。

示例

>>> from sympy import Point2D, pi
>>> t = Point2D(1, 0)
>>> t.rotate(pi/2)
Point2D(0, 1)
>>> t.rotate(pi/2, (2, 0))
Point2D(2, -1) 

参见

translate, scale

scale(x=1, y=1, pt=None)

通过在减去 pt(默认为 (0, 0))之后乘以 xy,然后再将 pt 加回来来缩放点的坐标(即 pt 是缩放的参考点)。

示例

>>> from sympy import Point2D
>>> t = Point2D(1, 1)
>>> t.scale(2)
Point2D(2, 1)
>>> t.scale(2, 2)
Point2D(2, 2) 

参见

rotate, translate

transform(matrix)

应用由 3x3 矩阵 matrix 描述的变换后的点。

参见

sympy.geometry.point.Point2D.rotate, sympy.geometry.point.Point2D.scale, sympy.geometry.point.Point2D.translate

translate(x=0, y=0)

将点移动,通过将 x 和 y 添加到点的坐标中。

示例

>>> from sympy import Point2D
>>> t = Point2D(0, 1)
>>> t.translate(2)
Point2D(2, 1)
>>> t.translate(2, 2)
Point2D(2, 3)
>>> t + Point2D(2, 2)
Point2D(2, 3) 

参见

sympy.geometry.point.Point2D.rotate, scale

property x

返回点的 X 坐标。

示例

>>> from sympy import Point2D
>>> p = Point2D(0, 1)
>>> p.x
0 
property y

返回点的 Y 坐标。

示例

>>> from sympy import Point2D
>>> p = Point2D(0, 1)
>>> p.y
1 
class sympy.geometry.point.Point3D(*args, _nocheck=False, **kwargs)

三维欧几里得空间中的一个点。

参数:

坐标

三个坐标值的序列。

抛出:

类型错误

尝试添加或减去不同维度的点时。调用 (intersection) 时使用的对象不是点。

示例

>>> from sympy import Point3D
>>> from sympy.abc import x
>>> Point3D(1, 2, 3)
Point3D(1, 2, 3)
>>> Point3D([1, 2, 3])
Point3D(1, 2, 3)
>>> Point3D(0, x, 3)
Point3D(0, x, 3) 

浮点数会自动转换为有理数,除非 evaluate 标志为 False:

>>> Point3D(0.5, 0.25, 2)
Point3D(1/2, 1/4, 2)
>>> Point3D(0.5, 0.25, 3, evaluate=False)
Point3D(0.5, 0.25, 3) 

属性

x
y
z
长度
static are_collinear(*points)

一系列点是否共线?

测试一组点是否共线。如果一组点共线,则返回 True,否则返回 False。

参数:

points : 点的序列

返回:

are_collinear : 布尔值

示例

>>> from sympy import Point3D
>>> from sympy.abc import x
>>> p1, p2 = Point3D(0, 0, 0), Point3D(1, 1, 1)
>>> p3, p4, p5 = Point3D(2, 2, 2), Point3D(x, x, x), Point3D(1, 2, 6)
>>> Point3D.are_collinear(p1, p2, p3, p4)
True
>>> Point3D.are_collinear(p1, p2, p3, p5)
False 

参见

sympy.geometry.line.Line3D

property coordinates

返回点的三个坐标。

示例

>>> from sympy import Point3D
>>> p = Point3D(0, 1, 2)
>>> p.coordinates
(0, 1, 2) 
direction_cosine(point)

给出两点之间的方向余弦

参数:

p:Point3D

返回:

列表

示例

>>> from sympy import Point3D
>>> p1 = Point3D(1, 2, 3)
>>> p1.direction_cosine(Point3D(2, 3, 5))
[sqrt(6)/6, sqrt(6)/6, sqrt(6)/3] 
direction_ratio(point)

给出两点之间的方向比率

参数:

p:Point3D

返回:

列表

示例

>>> from sympy import Point3D
>>> p1 = Point3D(1, 2, 3)
>>> p1.direction_ratio(Point3D(2, 3, 5))
[1, 1, 2] 
intersection(other)

这一点与另一个几何实体的交点。

参数:

other:几何实体或坐标序列

返回:

intersection:点的列表

注意

如果没有交点,则返回空列表;否则返回此点。

示例

>>> from sympy import Point3D
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, 0, 0)
>>> p1.intersection(p2)
[]
>>> p1.intersection(p3)
[Point3D(0, 0, 0)] 
scale(x=1, y=1, z=1, pt=None)

通过将点减去pt(默认为(0, 0)),然后乘以xy,再加回pt(即pt是缩放的参考点),来缩放点的坐标。

示例

>>> from sympy import Point3D
>>> t = Point3D(1, 1, 1)
>>> t.scale(2)
Point3D(2, 1, 1)
>>> t.scale(2, 2)
Point3D(2, 2, 1) 

参见

translate

transform(matrix)

应用描述为 4x4 矩阵matrix的变换后返回点。

参见

sympy.geometry.point.Point3D.scale, sympy.geometry.point.Point3D.translate

translate(x=0, y=0, z=0)

将点位移,通过将 x 和 y 添加到点的坐标中。

示例

>>> from sympy import Point3D
>>> t = Point3D(0, 1, 1)
>>> t.translate(2)
Point3D(2, 1, 1)
>>> t.translate(2, 2)
Point3D(2, 3, 1)
>>> t + Point3D(2, 2, 2)
Point3D(2, 3, 3) 

参见

scale

property x

返回点的 X 坐标。

示例

>>> from sympy import Point3D
>>> p = Point3D(0, 1, 3)
>>> p.x
0 
property y

返回点的 Y 坐标。

示例

>>> from sympy import Point3D
>>> p = Point3D(0, 1, 2)
>>> p.y
1 
property z

返回点的 Z 坐标。

示例

>>> from sympy import Point3D
>>> p = Point3D(0, 1, 1)
>>> p.z
1 

线

原文链接:docs.sympy.org/latest/modules/geometry/lines.html

class sympy.geometry.line.LinearEntity(p1, p2=None, **kwargs)

n-维欧几里得空间中所有线性实体(线、射线和线段)的基类。

注意

这是一个抽象类,不应被实例化。

另请参阅

sympy.geometry.entity.GeometryEntity

属性

环境维度
方向
长度
p1
p2
property ambient_dimension

返回线性实体对象的维度的属性方法。

参数:

p1:线性实体

返回:

维度:整数

示例

>>> from sympy import Point, Line
>>> p1, p2 = Point(0, 0), Point(1, 1)
>>> l1 = Line(p1, p2)
>>> l1.ambient_dimension
2 
>>> from sympy import Point, Line
>>> p1, p2 = Point(0, 0, 0), Point(1, 1, 1)
>>> l1 = Line(p1, p2)
>>> l1.ambient_dimension
3 
angle_between(l2)

返回由从原点发出方向与线性实体的方向向量相同的射线形成的非反射角。

参数:

l1:线性实体

l2:线性实体

返回:

角度:弧度制的角度

注意

根据向量 v1 和 v2 的点积,已知:

dot(v1, v2) = |v1|*|v2|*cos(A)

其中 A 是两个向量之间形成的角度。我们可以获取两条线的方向向量,并利用上述公式轻松找到两者之间的角度。

示例

>>> from sympy import Line
>>> e = Line((0, 0), (1, 0))
>>> ne = Line((0, 0), (1, 1))
>>> sw = Line((1, 1), (0, 0))
>>> ne.angle_between(e)
pi/4
>>> sw.angle_between(e)
3*pi/4 

要获取线交点处的非钝角,请使用smallest_angle_between方法:

>>> sw.smallest_angle_between(e)
pi/4 
>>> from sympy import Point3D, Line3D
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(-1, 2, 0)
>>> l1, l2 = Line3D(p1, p2), Line3D(p2, p3)
>>> l1.angle_between(l2)
acos(-sqrt(2)/3)
>>> l1.smallest_angle_between(l2)
acos(sqrt(2)/3) 

另请参阅

is_perpendicular, Ray2D.closing_angle

arbitrary_point(parameter='t')

线上的参数化点。

参数:

参数:字符串,可选

将用于参数点的参数的名称。默认值为‘t’。当此参数为 0 时,将返回用于定义线的第一个点,当它为 1 时,将返回第二个点。

返回:

:点

引发:

ValueError

当参数在线的定义中已经出现时。

示例

>>> from sympy import Point, Line
>>> p1, p2 = Point(1, 0), Point(5, 3)
>>> l1 = Line(p1, p2)
>>> l1.arbitrary_point()
Point2D(4*t + 1, 3*t)
>>> from sympy import Point3D, Line3D
>>> p1, p2 = Point3D(1, 0, 0), Point3D(5, 3, 1)
>>> l1 = Line3D(p1, p2)
>>> l1.arbitrary_point()
Point3D(4*t + 1, 3*t, t) 

另请参阅

sympy.geometry.point.Point

static are_concurrent(*lines)

一系列线性实体是否共线?

如果两个或更多线性实体在一个点相交,则它们是共线的。

参数:

线

一系列线性实体。

返回:

True:如果线性实体集合在一个点相交

False:否则。

示例

>>> from sympy import Point, Line
>>> p1, p2 = Point(0, 0), Point(3, 5)
>>> p3, p4 = Point(-2, -2), Point(0, 2)
>>> l1, l2, l3 = Line(p1, p2), Line(p1, p3), Line(p1, p4)
>>> Line.are_concurrent(l1, l2, l3)
True
>>> l4 = Line(p2, p3)
>>> Line.are_concurrent(l2, l3, l4)
False
>>> from sympy import Point3D, Line3D
>>> p1, p2 = Point3D(0, 0, 0), Point3D(3, 5, 2)
>>> p3, p4 = Point3D(-2, -2, -2), Point3D(0, 2, 1)
>>> l1, l2, l3 = Line3D(p1, p2), Line3D(p1, p3), Line3D(p1, p4)
>>> Line3D.are_concurrent(l1, l2, l3)
True
>>> l4 = Line3D(p2, p3)
>>> Line3D.are_concurrent(l2, l3, l4)
False 

另请参阅

sympy.geometry.util.intersection

bisectors(other)

返回通过自身和其他相交点的垂直线,这些相交点在同一平面上。

参数:

线:三维线

返回:

列表:两个线实例

示例

>>> from sympy import Point3D, Line3D
>>> r1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))
>>> r2 = Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))
>>> r1.bisectors(r2)
[Line3D(Point3D(0, 0, 0), Point3D(1, 1, 0)), Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))] 
contains(other)

子类应实现此方法,如果其他在自身的边界上则返回 True;如果不在自身的边界上则返回 False;如果无法确定则返回 None。

property direction

线性实体的方向向量。

返回:

p:一个点;从原点到该点的射线是

(self)的方向

示例

>>> from sympy import Line
>>> a, b = (1, 1), (1, 3)
>>> Line(a, b).direction
Point2D(0, 2)
>>> Line(b, a).direction
Point2D(0, -2) 

这可以报告从原点到的距离是 1:

>>> Line(b, a).direction.unit
Point2D(0, -1) 

参见

sympy.geometry.point.Point.unit

intersection(other)

与另一个几何实体的交点。

参数:

o:点或线性实体

返回:

intersection:几何实体的列表

示例

>>> from sympy import Point, Line, Segment
>>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7)
>>> l1 = Line(p1, p2)
>>> l1.intersection(p3)
[Point2D(7, 7)]
>>> p4, p5 = Point(5, 0), Point(0, 3)
>>> l2 = Line(p4, p5)
>>> l1.intersection(l2)
[Point2D(15/8, 15/8)]
>>> p6, p7 = Point(0, 5), Point(2, 6)
>>> s1 = Segment(p6, p7)
>>> l1.intersection(s1)
[]
>>> from sympy import Point3D, Line3D, Segment3D
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(7, 7, 7)
>>> l1 = Line3D(p1, p2)
>>> l1.intersection(p3)
[Point3D(7, 7, 7)]
>>> l1 = Line3D(Point3D(4,19,12), Point3D(5,25,17))
>>> l2 = Line3D(Point3D(-3, -15, -19), direction_ratio=[2,8,8])
>>> l1.intersection(l2)
[Point3D(1, 1, -3)]
>>> p6, p7 = Point3D(0, 5, 2), Point3D(2, 6, 3)
>>> s1 = Segment3D(p6, p7)
>>> l1.intersection(s1)
[] 

参见

sympy.geometry.point.Point

is_parallel(l2)

两个线性实体是否平行?

参数:

l1:线性实体

l2:线性实体

返回:

True:如果( l1 )和( l2 )平行,

False:否则。

示例

>>> from sympy import Point, Line
>>> p1, p2 = Point(0, 0), Point(1, 1)
>>> p3, p4 = Point(3, 4), Point(6, 7)
>>> l1, l2 = Line(p1, p2), Line(p3, p4)
>>> Line.is_parallel(l1, l2)
True
>>> p5 = Point(6, 6)
>>> l3 = Line(p3, p5)
>>> Line.is_parallel(l1, l3)
False
>>> from sympy import Point3D, Line3D
>>> p1, p2 = Point3D(0, 0, 0), Point3D(3, 4, 5)
>>> p3, p4 = Point3D(2, 1, 1), Point3D(8, 9, 11)
>>> l1, l2 = Line3D(p1, p2), Line3D(p3, p4)
>>> Line3D.is_parallel(l1, l2)
True
>>> p5 = Point3D(6, 6, 6)
>>> l3 = Line3D(p3, p5)
>>> Line3D.is_parallel(l1, l3)
False 

参见

coefficients

is_perpendicular(l2)

两个线性实体是否垂直?

参数:

l1:线性实体

l2:线性实体

返回:

True:如果( l1 )和( l2 )垂直,

False:否则。

示例

>>> from sympy import Point, Line
>>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(-1, 1)
>>> l1, l2 = Line(p1, p2), Line(p1, p3)
>>> l1.is_perpendicular(l2)
True
>>> p4 = Point(5, 3)
>>> l3 = Line(p1, p4)
>>> l1.is_perpendicular(l3)
False
>>> from sympy import Point3D, Line3D
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(-1, 2, 0)
>>> l1, l2 = Line3D(p1, p2), Line3D(p2, p3)
>>> l1.is_perpendicular(l2)
False
>>> p4 = Point3D(5, 3, 7)
>>> l3 = Line3D(p1, p4)
>>> l1.is_perpendicular(l3)
False 

参见

coefficients

is_similar(other)

如果 self 和其他位于同一条线上,则返回 True。

示例

>>> from sympy import Point, Line
>>> p1, p2, p3 = Point(0, 1), Point(3, 4), Point(2, 3)
>>> l1 = Line(p1, p2)
>>> l2 = Line(p1, p3)
>>> l1.is_similar(l2)
True 
property length

线的长度。

示例

>>> from sympy import Point, Line
>>> p1, p2 = Point(0, 0), Point(3, 5)
>>> l1 = Line(p1, p2)
>>> l1.length
oo 
property p1

线性实体的第一个定义点。

示例

>>> from sympy import Point, Line
>>> p1, p2 = Point(0, 0), Point(5, 3)
>>> l = Line(p1, p2)
>>> l.p1
Point2D(0, 0) 

参见

sympy.geometry.point.Point

property p2

线性实体的第二个定义点。

示例

>>> from sympy import Point, Line
>>> p1, p2 = Point(0, 0), Point(5, 3)
>>> l = Line(p1, p2)
>>> l.p2
Point2D(5, 3) 

参见

sympy.geometry.point.Point

parallel_line(p)

创建一条新的线,与通过点( p )的这个线性实体平行。

参数:

p:点

返回:

line:线

示例

>>> from sympy import Point, Line
>>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2)
>>> l1 = Line(p1, p2)
>>> l2 = l1.parallel_line(p3)
>>> p3 in l2
True
>>> l1.is_parallel(l2)
True
>>> from sympy import Point3D, Line3D
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0)
>>> l1 = Line3D(p1, p2)
>>> l2 = l1.parallel_line(p3)
>>> p3 in l2
True
>>> l1.is_parallel(l2)
True 

参见

is_parallel

perpendicular_line(p)

创建一条新的线,垂直于该线性实体,通过点( p )。

参数:

p:点

返回:

line:线

示例

>>> from sympy import Point3D, Line3D
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0)
>>> L = Line3D(p1, p2)
>>> P = L.perpendicular_line(p3); P
Line3D(Point3D(-2, 2, 0), Point3D(4/29, 6/29, 8/29))
>>> L.is_perpendicular(P)
True 

在三维空间中,定义线条的第一个点是需要通过的垂直线通过的点;第二个点(任意地)包含在给定的线条中:

>>> P.p2 in L
True 

参见

sympy.geometry.line.LinearEntity.is_perpendicular, perpendicular_segment

perpendicular_segment(p)

创建从( p )到这条线的垂直线段。

线段的端点是p和包含 self 的线中的最近点。(如果 self 不是一条线,则该点可能不在 self 中。)

参数:

p:点

返回:

segment:线段

注意

如果( p )在这个线性实体上,则返回( p )本身。

示例

>>> from sympy import Point, Line
>>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, 2)
>>> l1 = Line(p1, p2)
>>> s1 = l1.perpendicular_segment(p3)
>>> l1.is_perpendicular(s1)
True
>>> p3 in s1
True
>>> l1.perpendicular_segment(Point(4, 0))
Segment2D(Point2D(4, 0), Point2D(2, 2))
>>> from sympy import Point3D, Line3D
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, 2, 0)
>>> l1 = Line3D(p1, p2)
>>> s1 = l1.perpendicular_segment(p3)
>>> l1.is_perpendicular(s1)
True
>>> p3 in s1
True
>>> l1.perpendicular_segment(Point3D(4, 0, 0))
Segment3D(Point3D(4, 0, 0), Point3D(4/3, 4/3, 4/3)) 

参见

perpendicular_line

property points

用于定义这个线性实体的两个点。

返回:

points:点的元组

示例

>>> from sympy import Point, Line
>>> p1, p2 = Point(0, 0), Point(5, 11)
>>> l1 = Line(p1, p2)
>>> l1.points
(Point2D(0, 0), Point2D(5, 11)) 

参见

sympy.geometry.point.Point

projection(other)

将点、线、射线或线段投影到此线性实体上。

参数:

other:点或线性实体(线、射线、线段)

返回:

投影:点或线性实体(线、射线、线段)

返回类型与参数other的类型匹配。

引发:

几何错误

当方法无法执行投影时。

注意

投影涉及取两个定义线性实体的点,并将这些点投影到一条线上,然后使用这些投影重新形成线性实体。 点 P 通过找到距离 P 最近的 L 上的点来投影到线 L 上。 此点是与通过 P 的垂直于 L 的线的 L 的交点。

示例

>>> from sympy import Point, Line, Segment, Rational
>>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(Rational(1, 2), 0)
>>> l1 = Line(p1, p2)
>>> l1.projection(p3)
Point2D(1/4, 1/4)
>>> p4, p5 = Point(10, 0), Point(12, 1)
>>> s1 = Segment(p4, p5)
>>> l1.projection(s1)
Segment2D(Point2D(5, 5), Point2D(13/2, 13/2))
>>> p1, p2, p3 = Point(0, 0, 1), Point(1, 1, 2), Point(2, 0, 1)
>>> l1 = Line(p1, p2)
>>> l1.projection(p3)
Point3D(2/3, 2/3, 5/3)
>>> p4, p5 = Point(10, 0, 1), Point(12, 1, 3)
>>> s1 = Segment(p4, p5)
>>> l1.projection(s1)
Segment3D(Point3D(10/3, 10/3, 13/3), Point3D(5, 5, 6)) 

另请参见

sympy.geometry.point.Point, perpendicular_line

random_point(seed=None)

线性实体上的随机点。

返回:

point:点

示例

>>> from sympy import Point, Line, Ray, Segment
>>> p1, p2 = Point(0, 0), Point(5, 3)
>>> line = Line(p1, p2)
>>> r = line.random_point(seed=42)  # seed value is optional
>>> r.n(3)
Point2D(-0.72, -0.432)
>>> r in line
True
>>> Ray(p1, p2).random_point(seed=42).n(3)
Point2D(0.72, 0.432)
>>> Segment(p1, p2).random_point(seed=42).n(3)
Point2D(3.2, 1.92) 

另请参见

sympy.geometry.point.Point

smallest_angle_between(l2)

返回形成线性实体包含的线的交点处的最小角度。

参数:

l1:线性实体

l2:线性实体

返回:

角度:弧度角

示例

>>> from sympy import Point, Line
>>> p1, p2, p3 = Point(0, 0), Point(0, 4), Point(2, -2)
>>> l1, l2 = Line(p1, p2), Line(p1, p3)
>>> l1.smallest_angle_between(l2)
pi/4 

另请参见

angle_between, is_perpendicular, Ray2D.closing_angle

class sympy.geometry.line.Line(*args, **kwargs)

空间中的无限直线。

使用两个不同的点、点和斜率或方程式声明 2D 线。可以用点和方向比例定义 3D 线。

参数:

p1:点

p2:点

斜率:SymPy 表达式

direction_ratio:列表

equation:线的方程

注意

(Line)将根据(p1)的维度自动子类化为(Line2D)或(Line3D)。 (slope)参数仅与(Line2D)相关,(direction_ratio)参数仅与(Line3D)相关。

点的顺序将定义用于计算线之间角度的线的方向。

示例

>>> from sympy import Line, Segment, Point, Eq
>>> from sympy.abc import x, y, a, b 
>>> L = Line(Point(2,3), Point(3,5))
>>> L
Line2D(Point2D(2, 3), Point2D(3, 5))
>>> L.points
(Point2D(2, 3), Point2D(3, 5))
>>> L.equation()
-2*x + y + 1
>>> L.coefficients
(-2, 1, 1) 

使用关键字slope进行实例化:

>>> Line(Point(0, 0), slope=0)
Line2D(Point2D(0, 0), Point2D(1, 0)) 

用另一个线性对象实例化

>>> s = Segment((0, 0), (0, 1))
>>> Line(s).equation()
x 

对应于方程(ax + by + c = 0)的线,可以输入:

>>> Line(3*x + y + 18)
Line2D(Point2D(0, -18), Point2D(1, -21)) 

如果(x)或(y)有不同的名称,则也可以指定为字符串(以匹配名称)或符号:

>>> Line(Eq(3*a + b, -18), x='a', y=b)
Line2D(Point2D(0, -18), Point2D(1, -21)) 

另请参见

sympy.geometry.point.Point, sympy.geometry.line.Line2D, sympy.geometry.line.Line3D

contains(other)

如果 (other) 在此直线上,则返回 True;否则返回 False。

示例

>>> from sympy import Line,Point
>>> p1, p2 = Point(0, 1), Point(3, 4)
>>> l = Line(p1, p2)
>>> l.contains(p1)
True
>>> l.contains((0, 1))
True
>>> l.contains((0, 0))
False
>>> a = (0, 0, 0)
>>> b = (1, 1, 1)
>>> c = (2, 2, 2)
>>> l1 = Line(a, b)
>>> l2 = Line(b, a)
>>> l1 == l2
False
>>> l1 in l2
True 
distance(other)

查找线与点之间的最短距离。

引发:

如果 other 不是点,则会引发 NotImplementedError

示例

>>> from sympy import Point, Line
>>> p1, p2 = Point(0, 0), Point(1, 1)
>>> s = Line(p1, p2)
>>> s.distance(Point(-1, 1))
sqrt(2)
>>> s.distance((-1, 2))
3*sqrt(2)/2
>>> p1, p2 = Point(0, 0, 0), Point(1, 1, 1)
>>> s = Line(p1, p2)
>>> s.distance(Point(-1, 1, 1))
2*sqrt(6)/3
>>> s.distance((-1, 1, 1))
2*sqrt(6)/3 
equals(other)

如果自身与其他数学实体相同,则返回 True。

plot_interval(parameter='t')

线的默认几何图形绘制区间。提供将产生长度为 +/- 5 个单位的线的值(其中单位是定义线的两点之间的距离)。

参数:

parameter:字符串,可选

默认值为 't'。

返回:

plot_interval:列表(绘图区间)

[parameter, lower_bound, upper_bound]

示例

>>> from sympy import Point, Line
>>> p1, p2 = Point(0, 0), Point(5, 3)
>>> l1 = Line(p1, p2)
>>> l1.plot_interval()
[t, -5, 5] 
class sympy.geometry.line.Ray(p1, p2=None, **kwargs)

射线是空间中的半线,具有源点和方向。

参数:

p1:点

射线的源点

p2:点或弧度值

此点确定射线传播的方向。如果以角度给出,则按弧度解释,正方向为逆时针。

注意

(Ray) 将根据 (p1) 的维度自动分为 (Ray2D) 或 (Ray3D)。

示例

>>> from sympy import Ray, Point, pi
>>> r = Ray(Point(2, 3), Point(3, 5))
>>> r
Ray2D(Point2D(2, 3), Point2D(3, 5))
>>> r.points
(Point2D(2, 3), Point2D(3, 5))
>>> r.source
Point2D(2, 3)
>>> r.xdirection
oo
>>> r.ydirection
oo
>>> r.slope
2
>>> Ray(Point(0, 0), angle=pi/4).slope
1 

另请参阅

sympy.geometry.line.Ray2Dsympy.geometry.line.Ray3Dsympy.geometry.point.Pointsympy.geometry.line.Line

属性

source
contains(other)

其他几何实体是否包含在此射线内?

示例

>>> from sympy import Ray,Point,Segment
>>> p1, p2 = Point(0, 0), Point(4, 4)
>>> r = Ray(p1, p2)
>>> r.contains(p1)
True
>>> r.contains((1, 1))
True
>>> r.contains((1, 3))
False
>>> s = Segment((1, 1), (2, 2))
>>> r.contains(s)
True
>>> s = Segment((1, 2), (2, 5))
>>> r.contains(s)
False
>>> r1 = Ray((2, 2), (3, 3))
>>> r.contains(r1)
True
>>> r1 = Ray((2, 2), (3, 5))
>>> r.contains(r1)
False 
distance(other)

查找射线与点之间的最短距离。

引发:

如果 other 不是点,则会引发 NotImplementedError

示例

>>> from sympy import Point, Ray
>>> p1, p2 = Point(0, 0), Point(1, 1)
>>> s = Ray(p1, p2)
>>> s.distance(Point(-1, -1))
sqrt(2)
>>> s.distance((-1, 2))
3*sqrt(2)/2
>>> p1, p2 = Point(0, 0, 0), Point(1, 1, 2)
>>> s = Ray(p1, p2)
>>> s
Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 2))
>>> s.distance(Point(-1, -1, 2))
4*sqrt(3)/3
>>> s.distance((-1, -1, 2))
4*sqrt(3)/3 
equals(other)

如果自身与其他数学实体相同,则返回 True。

plot_interval(parameter='t')

射线的默认几何图形绘制区间。提供将产生长度为 10 个单位的射线的值(其中单位是定义射线的两点之间的距离)。

参数:

parameter:字符串,可选

默认值为 't'。

返回:

plot_interval:列表

[parameter, lower_bound, upper_bound]

示例

>>> from sympy import Ray, pi
>>> r = Ray((0, 0), angle=pi/4)
>>> r.plot_interval()
[t, 0, 10] 
property source

射线发出的点。

示例

>>> from sympy import Point, Ray
>>> p1, p2 = Point(0, 0), Point(4, 1)
>>> r1 = Ray(p1, p2)
>>> r1.source
Point2D(0, 0)
>>> p1, p2 = Point(0, 0, 0), Point(4, 1, 5)
>>> r1 = Ray(p2, p1)
>>> r1.source
Point3D(4, 1, 5) 

另请参阅

sympy.geometry.point.Point

class sympy.geometry.line.Segment(p1, p2, **kwargs)

空间中的线段。

参数:

p1:点

p2:点

注意

如果使用 2D 或 3D 点来定义 (Segment),它将自动分为 (Segment2D) 或 (Segment3D)。

示例

>>> from sympy import Point, Segment
>>> Segment((1, 0), (1, 1)) # tuples are interpreted as pts
Segment2D(Point2D(1, 0), Point2D(1, 1))
>>> s = Segment(Point(4, 3), Point(1, 1))
>>> s.points
(Point2D(4, 3), Point2D(1, 1))
>>> s.slope
2/3
>>> s.length
sqrt(13)
>>> s.midpoint
Point2D(5/2, 2)
>>> Segment((1, 0, 0), (1, 1, 1)) # tuples are interpreted as pts
Segment3D(Point3D(1, 0, 0), Point3D(1, 1, 1))
>>> s = Segment(Point(4, 3, 9), Point(1, 1, 7)); s
Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7))
>>> s.points
(Point3D(4, 3, 9), Point3D(1, 1, 7))
>>> s.length
sqrt(17)
>>> s.midpoint
Point3D(5/2, 2, 8) 

另请参阅

sympy.geometry.line.Segment2Dsympy.geometry.line.Segment3Dsympy.geometry.point.Pointsympy.geometry.line.Line

属性

length (数字或 SymPy 表达式)
midpoint (点)
contains(other)

其他几何实体是否包含在此线段内?

示例

>>> from sympy import Point, Segment
>>> p1, p2 = Point(0, 1), Point(3, 4)
>>> s = Segment(p1, p2)
>>> s2 = Segment(p2, p1)
>>> s.contains(s2)
True
>>> from sympy import Point3D, Segment3D
>>> p1, p2 = Point3D(0, 1, 1), Point3D(3, 4, 5)
>>> s = Segment3D(p1, p2)
>>> s2 = Segment3D(p2, p1)
>>> s.contains(s2)
True
>>> s.contains((p1 + p2)/2)
True 
distance(other)

查找线段与点之间的最短距离。

引发:

如果other不是点,则抛出NotImplementedError

示例

>>> from sympy import Point, Segment
>>> p1, p2 = Point(0, 1), Point(3, 4)
>>> s = Segment(p1, p2)
>>> s.distance(Point(10, 15))
sqrt(170)
>>> s.distance((0, 12))
sqrt(73)
>>> from sympy import Point3D, Segment3D
>>> p1, p2 = Point3D(0, 0, 3), Point3D(1, 1, 4)
>>> s = Segment3D(p1, p2)
>>> s.distance(Point3D(10, 15, 12))
sqrt(341)
>>> s.distance((10, 15, 12))
sqrt(341) 
equals(other)

如果 self 和 other 是相同的数学实体则返回 True

property length

线段的长度。

示例

>>> from sympy import Point, Segment
>>> p1, p2 = Point(0, 0), Point(4, 3)
>>> s1 = Segment(p1, p2)
>>> s1.length
5
>>> from sympy import Point3D, Segment3D
>>> p1, p2 = Point3D(0, 0, 0), Point3D(4, 3, 3)
>>> s1 = Segment3D(p1, p2)
>>> s1.length
sqrt(34) 

参见

sympy.geometry.point.Point.distance

property midpoint

线段的中点。

示例

>>> from sympy import Point, Segment
>>> p1, p2 = Point(0, 0), Point(4, 3)
>>> s1 = Segment(p1, p2)
>>> s1.midpoint
Point2D(2, 3/2)
>>> from sympy import Point3D, Segment3D
>>> p1, p2 = Point3D(0, 0, 0), Point3D(4, 3, 3)
>>> s1 = Segment3D(p1, p2)
>>> s1.midpoint
Point3D(2, 3/2, 3/2) 

参见

sympy.geometry.point.Point.midpoint

perpendicular_bisector(p=None)

此线段的垂直平分线。

如果未指定点或指定的点不在平分线上,则返回平分线作为线。否则,返回一个连接指定点和平分线与线段交点的段。

参数:

p:点

返回:

bisector:线或段

示例

>>> from sympy import Point, Segment
>>> p1, p2, p3 = Point(0, 0), Point(6, 6), Point(5, 1)
>>> s1 = Segment(p1, p2)
>>> s1.perpendicular_bisector()
Line2D(Point2D(3, 3), Point2D(-3, 9)) 
>>> s1.perpendicular_bisector(p3)
Segment2D(Point2D(5, 1), Point2D(3, 3)) 

参见

LinearEntity.perpendicular_segment

plot_interval(parameter='t')

Segment 的默认几何绘图的绘图区间给出将在绘图中生成完整线段的值。

参数:

parameter:str,可选

默认值为‘t’。

返回:

plot_interval:列表

[参数, 下界, 上界]

示例

>>> from sympy import Point, Segment
>>> p1, p2 = Point(0, 0), Point(5, 3)
>>> s1 = Segment(p1, p2)
>>> s1.plot_interval()
[t, 0, 1] 
class sympy.geometry.line.LinearEntity2D(p1, p2=None, **kwargs)

在二维欧几里德空间中所有线性实体(直线、射线和线段)的基类。

注意

这是一个抽象类,不能被实例化。

参见

sympy.geometry.entity.GeometryEntity

属性

p1
p2
系数
斜率
property bounds

返回一个元组(xmin,ymin,xmax,ymax),表示几何图形的边界矩形。

perpendicular_line(p)

创建一个通过点(p)且垂直于此线性实体的新线。

参数:

p:点

返回:

line:线

示例

>>> from sympy import Point, Line
>>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2)
>>> L = Line(p1, p2)
>>> P = L.perpendicular_line(p3); P
Line2D(Point2D(-2, 2), Point2D(-5, 4))
>>> L.is_perpendicular(P)
True 

在二维空间中,垂直线的第一个点是必须经过的点;第二个点是任意选择的。要获得明确使用线中的点的线,请从线到点的垂直线段创建一条线:

>>> Line(L.perpendicular_segment(p3))
Line2D(Point2D(-2, 2), Point2D(4/13, 6/13)) 

参见

sympy.geometry.line.LinearEntity.is_perpendicularperpendicular_segment

property slope

此线性实体的斜率,如果是垂直线则为无穷大。

返回:

slope:数字或 SymPy 表达式

示例

>>> from sympy import Point, Line
>>> p1, p2 = Point(0, 0), Point(3, 5)
>>> l1 = Line(p1, p2)
>>> l1.slope
5/3 
>>> p3 = Point(0, 4)
>>> l2 = Line(p1, p3)
>>> l2.slope
oo 

参见

coefficients

class sympy.geometry.line.Line2D(p1, pt=None, slope=None, **kwargs)

二维空间中的无限直线。

一条线由两个不同的点或使用关键字(slope)定义的点和斜率声明。

参数:

p1:点

pt:点

slope:SymPy 表达式

示例

>>> from sympy import Line, Segment, Point
>>> L = Line(Point(2,3), Point(3,5))
>>> L
Line2D(Point2D(2, 3), Point2D(3, 5))
>>> L.points
(Point2D(2, 3), Point2D(3, 5))
>>> L.equation()
-2*x + y + 1
>>> L.coefficients
(-2, 1, 1) 

使用关键字slope实例化:

>>> Line(Point(0, 0), slope=0)
Line2D(Point2D(0, 0), Point2D(1, 0)) 

使用另一个线性对象实例化

>>> s = Segment((0, 0), (0, 1))
>>> Line(s).equation()
x 

参见

sympy.geometry.point.Point

property coefficients

方程 (ax + by + c = 0) 的系数 ((a, b, c))。

示例

>>> from sympy import Point, Line
>>> from sympy.abc import x, y
>>> p1, p2 = Point(0, 0), Point(5, 3)
>>> l = Line(p1, p2)
>>> l.coefficients
(-3, 5, 0) 
>>> p3 = Point(x, y)
>>> l2 = Line(p1, p3)
>>> l2.coefficients
(-y, x, 0) 

另见

sympy.geometry.line.Line2D.equation

equation(x='x', y='y')

线的方程:ax + by + c。

参数:

x : str, 可选项

用于 x 轴的名称,默认值为 'x'。

y : str, 可选项

用于 y 轴的名称,默认值为 'y'。

返回:

equation : SymPy 表达式

示例

>>> from sympy import Point, Line
>>> p1, p2 = Point(1, 0), Point(5, 3)
>>> l1 = Line(p1, p2)
>>> l1.equation()
-3*x + 4*y + 3 

另见

sympy.geometry.line.Line2D.coefficients

class sympy.geometry.line.Ray2D(p1, pt=None, angle=None, **kwargs)

光线是空间中带有源点和方向的半线。

参数:

p1 : 点

光线的来源

p2 : 点或弧度值

此点确定射线传播的方向。若作为角度给出,则解释为弧度,正方向为逆时针方向。

示例

>>> from sympy import Point, pi, Ray
>>> r = Ray(Point(2, 3), Point(3, 5))
>>> r
Ray2D(Point2D(2, 3), Point2D(3, 5))
>>> r.points
(Point2D(2, 3), Point2D(3, 5))
>>> r.source
Point2D(2, 3)
>>> r.xdirection
oo
>>> r.ydirection
oo
>>> r.slope
2
>>> Ray(Point(0, 0), angle=pi/4).slope
1 

另见

sympy.geometry.point.Point, Line

属性

源点
x 方向
y 方向
closing_angle(r2)

返回 r2 必须旋转的角度,以使其面对与 r1 相同的方向。

参数:

r1 : Ray2D

r2 : Ray2D

返回:

angle : 弧度制的角度(逆时针角度为正)

示例

>>> from sympy import Ray, pi
>>> r1 = Ray((0, 0), (1, 0))
>>> r2 = r1.rotate(-pi/2)
>>> angle = r1.closing_angle(r2); angle
pi/2
>>> r2.rotate(angle).direction.unit == r1.direction.unit
True
>>> r2.closing_angle(r1)
-pi/2 

另见

LinearEntity.angle_between

property xdirection

光线的 x 方向。

如果光线指向正 x 方向则为正无穷,如果光线指向负 x 方向则为负无穷,若光线为竖直则为 0。

示例

>>> from sympy import Point, Ray
>>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, -1)
>>> r1, r2 = Ray(p1, p2), Ray(p1, p3)
>>> r1.xdirection
oo
>>> r2.xdirection
0 

另见

ydirection

property ydirection

光线的 y 方向。

如果光线指向正 y 方向则为正无穷,如果光线指向负 y 方向则为负无穷,若光线为水平则为 0。

示例

>>> from sympy import Point, Ray
>>> p1, p2, p3 = Point(0, 0), Point(-1, -1), Point(-1, 0)
>>> r1, r2 = Ray(p1, p2), Ray(p1, p3)
>>> r1.ydirection
-oo
>>> r2.ydirection
0 

另见

xdirection

class sympy.geometry.line.Segment2D(p1, p2, **kwargs)

2D 空间中的线段。

参数:

p1 : 点

p2 : 点

示例

>>> from sympy import Point, Segment
>>> Segment((1, 0), (1, 1)) # tuples are interpreted as pts
Segment2D(Point2D(1, 0), Point2D(1, 1))
>>> s = Segment(Point(4, 3), Point(1, 1)); s
Segment2D(Point2D(4, 3), Point2D(1, 1))
>>> s.points
(Point2D(4, 3), Point2D(1, 1))
>>> s.slope
2/3
>>> s.length
sqrt(13)
>>> s.midpoint
Point2D(5/2, 2) 

另见

sympy.geometry.point.Point, Line

属性

长度 (数字或 SymPy 表达式)
中点 (点)
class sympy.geometry.line.LinearEntity3D(p1, p2, **kwargs)

所有在三维欧几里得空间中的线性实体(线、射线和线段)的基类。

注释

这是一个基类,不应该被实例化。

属性

p1
p2
方向比
方向余弦
property direction_cosine

3D 空间中给定直线的归一化方向比。

示例

>>> from sympy import Point3D, Line3D
>>> p1, p2 = Point3D(0, 0, 0), Point3D(5, 3, 1)
>>> l = Line3D(p1, p2)
>>> l.direction_cosine
[sqrt(35)/7, 3*sqrt(35)/35, sqrt(35)/35]
>>> sum(i**2 for i in _)
1 

另见

sympy.geometry.line.Line3D.equation

property direction_ratio

3D 空间中给定直线的方向比。

示例

>>> from sympy import Point3D, Line3D
>>> p1, p2 = Point3D(0, 0, 0), Point3D(5, 3, 1)
>>> l = Line3D(p1, p2)
>>> l.direction_ratio
[5, 3, 1] 

另见

sympy.geometry.line.Line3D.equation

class sympy.geometry.line.Line3D(p1, pt=None, direction_ratio=(), **kwargs)

3D 空间中的无限线。

用两个不同点或使用关键字(direction_ratio)定义的点和方向比例声明一条线。

参数:

p1 : Point3D

pt : Point3D

direction_ratio : 列表

示例

>>> from sympy import Line3D, Point3D
>>> L = Line3D(Point3D(2, 3, 4), Point3D(3, 5, 1))
>>> L
Line3D(Point3D(2, 3, 4), Point3D(3, 5, 1))
>>> L.points
(Point3D(2, 3, 4), Point3D(3, 5, 1)) 

参见

sympy.geometry.point.Point3D, sympy.geometry.line.Line, sympy.geometry.line.Line2D

distance(other)

查找线与另一个对象之间的最短距离。

参数:

Point3D, Line3D, Plane, tuple, list

返回:

距离

注意

此方法只接受 3D 实体作为其参数

元组和列表转换为 Point3D,因此必须是长度为 3、2 或 1。

如果(other)不是指定类(Point3D、Line3D 或 Plane)的实例,则引发 NotImplementedError。

示例

>>> from sympy.geometry import Line3D
>>> l1 = Line3D((0, 0, 0), (0, 0, 1))
>>> l2 = Line3D((0, 1, 0), (1, 1, 1))
>>> l1.distance(l2)
1 

计算得到的距离可能也是符号的:

>>> from sympy.abc import x, y
>>> l1 = Line3D((0, 0, 0), (0, 0, 1))
>>> l2 = Line3D((0, x, 0), (y, x, 1))
>>> l1.distance(l2)
Abs(x*y)/Abs(sqrt(y**2)) 
equation(x='x', y='y', z='z')

返回在 3D 中定义线的方程。

参数:

x : 字符串,可选

用于 x 轴的名称,默认值为‘x’。

y : 字符串,可选

用于 y 轴的名称,默认值为‘y’。

z : 字符串,可选

用于 z 轴的名称,默认值为‘z’。

返回:

equation : 同时方程组的元组

示例

>>> from sympy import Point3D, Line3D, solve
>>> from sympy.abc import x, y, z
>>> p1, p2 = Point3D(1, 0, 0), Point3D(5, 3, 0)
>>> l1 = Line3D(p1, p2)
>>> eq = l1.equation(x, y, z); eq
(-3*x + 4*y + 3, z)
>>> solve(eq.subs(z, 0), (x, y, z))
{x: 4*y/3 + 1} 
class sympy.geometry.line.Ray3D(p1, pt=None, direction_ratio=(), **kwargs)

射线是带有源点和方向的空间半线。

参数:

p1 : Point3D

射线的源点

p2 : 点或方向向量

direction_ratio: 确定射线传播的方向。

示例

>>> from sympy import Point3D, Ray3D
>>> r = Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0))
>>> r
Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0))
>>> r.points
(Point3D(2, 3, 4), Point3D(3, 5, 0))
>>> r.source
Point3D(2, 3, 4)
>>> r.xdirection
oo
>>> r.ydirection
oo
>>> r.direction_ratio
[1, 2, -4] 

参见

sympy.geometry.point.Point3D, Line3D

属性

source
xdirection
ydirection
zdirection
property xdirection

射线的 x 方向。

如果射线指向正 x 方向则为正无穷,如果射线指向负 x 方向则为负无穷,如果射线为竖直则为 0。

示例

>>> from sympy import Point3D, Ray3D
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, -1, 0)
>>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
>>> r1.xdirection
oo
>>> r2.xdirection
0 

参见

ydirection

property ydirection

射线的 y 方向。

如果射线指向正 y 方向则为正无穷,如果射线指向负 y 方向则为负无穷,如果射线为水平则为 0。

示例

>>> from sympy import Point3D, Ray3D
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0)
>>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
>>> r1.ydirection
-oo
>>> r2.ydirection
0 

参见

xdirection

property zdirection

射线的 z 方向。

如果射线指向正 z 方向则为正无穷,如果射线指向负 z 方向则为负无穷,如果射线为水平则为 0。

示例

>>> from sympy import Point3D, Ray3D
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0)
>>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
>>> r1.ydirection
-oo
>>> r2.ydirection
0
>>> r2.zdirection
0 

参见

xdirection

class sympy.geometry.line.Segment3D(p1, p2, **kwargs)

3D 空间中的线段。

参数:

p1 : Point3D

p2 : Point3D

示例

>>> from sympy import Point3D, Segment3D
>>> Segment3D((1, 0, 0), (1, 1, 1)) # tuples are interpreted as pts
Segment3D(Point3D(1, 0, 0), Point3D(1, 1, 1))
>>> s = Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7)); s
Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7))
>>> s.points
(Point3D(4, 3, 9), Point3D(1, 1, 7))
>>> s.length
sqrt(17)
>>> s.midpoint
Point3D(5/2, 2, 8) 

参见

sympy.geometry.point.Point3D, Line3D

属性

length (number or SymPy expression)
midpoint (Point3D)
posted @ 2024-06-27 17:14  绝不原创的飞龙  阅读(291)  评论(0)    收藏  举报