• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python compatibility.u函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sympy.core.compatibility.u函数的典型用法代码示例。如果您正苦于以下问题:Python u函数的具体用法?Python u怎么用?Python u使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了u函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_commutator

def test_commutator():
    A = Operator('A')
    B = Operator('B')
    c = Commutator(A, B)
    c_tall = Commutator(A**2, B)
    assert str(c) == '[A,B]'
    assert pretty(c) == '[A,B]'
    assert upretty(c) == u('[A,B]')
    assert latex(c) == r'\left[A,B\right]'
    sT(c, "Commutator(Operator(Symbol('A')),Operator(Symbol('B')))")
    assert str(c_tall) == '[A**2,B]'
    ascii_str = \
"""\
[ 2  ]\n\
[A ,B]\
"""
    ucode_str = \
u("""\
⎡ 2  ⎤\n\
⎣A ,B⎦\
""")
    assert pretty(c_tall) == ascii_str
    assert upretty(c_tall) == ucode_str
    assert latex(c_tall) == r'\left[\left(A\right)^{2},B\right]'
    sT(c_tall, "Commutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
开发者ID:B-Rich,项目名称:sympy,代码行数:25,代码来源:test_printing.py


示例2: test_dyadic_pretty_print

def test_dyadic_pretty_print():

    expected = """\
 2
a  n_x|n_y + b n_y|n_y + c*sin(alpha) n_z|n_y\
"""

    uexpected = u("""\
 2
a  n_x⊗n_y + b n_y⊗n_y + c⋅sin(α) n_z⊗n_y\
""")
    assert ascii_vpretty(y) == expected
    assert unicode_vpretty(y) == uexpected

    expected = u('alpha n_x|n_x + sin(omega) n_y|n_z + alpha*beta n_z|n_x')
    uexpected = u('α n_x⊗n_x + sin(ω) n_y⊗n_z + α⋅β n_z⊗n_x')
    assert ascii_vpretty(x) == expected
    assert unicode_vpretty(x) == uexpected

    assert ascii_vpretty(Dyadic([])) == '0'
    assert unicode_vpretty(Dyadic([])) == '0'

    assert ascii_vpretty(xx) == '- n_x|n_y - n_x|n_z'
    assert unicode_vpretty(xx) == u('- n_x⊗n_y - n_x⊗n_z')

    assert ascii_vpretty(xx2) == 'n_x|n_y + n_x|n_z'
    assert unicode_vpretty(xx2) == u('n_x⊗n_y + n_x⊗n_z')
开发者ID:asmeurer,项目名称:sympy,代码行数:27,代码来源:test_printing.py


示例3: test_vector_pretty_print

def test_vector_pretty_print():

    # TODO : The unit vectors should print with subscripts but they just
    # print as `n_x` instead of making `x` a subscript with unicode.

    # TODO : The pretty print division does not print correctly here:
    # w = alpha * N.x + sin(omega) * N.y + alpha / beta * N.z

    expected = """\
 2
a  n_x + b n_y + c*sin(alpha) n_z\
"""
    uexpected = u("""\
 2
a  n_x + b n_y + c⋅sin(α) n_z\
""")


    assert ascii_vpretty(v) == expected
    assert unicode_vpretty(v) == uexpected

    expected = u('alpha n_x + sin(omega) n_y + alpha*beta n_z')
    uexpected = u('α n_x + sin(ω) n_y + α⋅β n_z')

    assert ascii_vpretty(w) == expected
    assert unicode_vpretty(w) == uexpected
开发者ID:AdrianPotter,项目名称:sympy,代码行数:26,代码来源:test_printing.py


示例4: annotated

def annotated(letter):
    """
    Return a stylised drawing of the letter ``letter``, together with
    information on how to put annotations (super- and subscripts to the
    left and to the right) on it.

    See pretty.py functions _print_meijerg, _print_hyper on how to use this
    information.
    """
    ucode_pics = {
        'F': (2, 0, 2, 0, u('\N{BOX DRAWINGS LIGHT DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n'
                            '\N{BOX DRAWINGS LIGHT VERTICAL AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n'
                            '\N{BOX DRAWINGS LIGHT UP}')),
        'G': (3, 0, 3, 1,
              u('\N{BOX DRAWINGS LIGHT ARC DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC DOWN AND LEFT}\n'
                '\N{BOX DRAWINGS LIGHT VERTICAL}\N{BOX DRAWINGS LIGHT RIGHT}\N{BOX DRAWINGS LIGHT DOWN AND LEFT}\n'
                '\N{BOX DRAWINGS LIGHT ARC UP AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC UP AND LEFT}'))
    }
    ascii_pics = {
        'F': (3, 0, 3, 0, ' _\n|_\n|\n'),
        'G': (3, 0, 3, 1, ' __\n/__\n\_|')
    }

    if _use_unicode:
        return ucode_pics[letter]
    else:
        return ascii_pics[letter]
开发者ID:AdrianPotter,项目名称:sympy,代码行数:27,代码来源:pretty_symbology.py


示例5: test_ipythonprinting

def test_ipythonprinting():
    # Initialize and setup IPython session
    app = init_ipython_session()
    app.run_cell("ip = get_ipython()")
    app.run_cell("inst = ip.instance()")
    app.run_cell("format = inst.display_formatter.format")
    app.run_cell("from sympy import Symbol")

    # Printing without printing extension
    app.run_cell("a = format(Symbol('pi'))")
    app.run_cell("a2 = format(Symbol('pi')**2)")
    # Deal with API change starting at IPython 1.0
    if int(ipython.__version__.split(".")[0]) < 1:
        assert app.user_ns['a']['text/plain'] == "pi"
        assert app.user_ns['a2']['text/plain'] == "pi**2"
    else:
        assert app.user_ns['a'][0]['text/plain'] == "pi"
        assert app.user_ns['a2'][0]['text/plain'] == "pi**2"

    # Load printing extension
    app.run_cell("from sympy import init_printing")
    app.run_cell("init_printing()")
    # Printing with printing extension
    app.run_cell("a = format(Symbol('pi'))")
    app.run_cell("a2 = format(Symbol('pi')**2)")
    # Deal with API change starting at IPython 1.0
    if int(ipython.__version__.split(".")[0]) < 1:
        assert app.user_ns['a']['text/plain'] in (u('\N{GREEK SMALL LETTER PI}'), 'pi')
        assert app.user_ns['a2']['text/plain'] in (u(' 2\n\N{GREEK SMALL LETTER PI} '), '  2\npi ')
    else:
        assert app.user_ns['a'][0]['text/plain'] in (u('\N{GREEK SMALL LETTER PI}'), 'pi')
        assert app.user_ns['a2'][0]['text/plain'] in (u(' 2\n\N{GREEK SMALL LETTER PI} '), '  2\npi ')
开发者ID:A-turing-machine,项目名称:sympy,代码行数:32,代码来源:test_ipythonprinting.py


示例6: test_print_builtin_option

def test_print_builtin_option():
    # Initialize and setup IPython session
    app = init_ipython_session()
    app.run_cell("ip = get_ipython()")
    app.run_cell("inst = ip.instance()")
    app.run_cell("format = inst.display_formatter.format")
    app.run_cell("from sympy import Symbol")
    app.run_cell("from sympy import init_printing")

    app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
    # Deal with API change starting at IPython 1.0
    if int(ipython.__version__.split(".")[0]) < 1:
        text = app.user_ns['a']['text/plain']
        raises(KeyError, lambda: app.user_ns['a']['text/latex'])
    else:
        text = app.user_ns['a'][0]['text/plain']
        raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
    # Note : Unicode of Python2 is equivalent to str in Python3. In Python 3 we have one
    # text type: str which holds Unicode data and two byte types bytes and bytearray.
    # XXX: How can we make this ignore the terminal width? This test fails if
    # the terminal is too narrow.
    assert text in ("{pi: 3.14, n_i: 3}",
                    u('{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}'),
                    "{n_i: 3, pi: 3.14}",
                    u('{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}'))

    # If we enable the default printing, then the dictionary's should render
    # as a LaTeX version of the whole dict: ${\pi: 3.14, n_i: 3}$
    app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
    app.run_cell("init_printing(use_latex=True)")
    app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
    # Deal with API change starting at IPython 1.0
    if int(ipython.__version__.split(".")[0]) < 1:
        text = app.user_ns['a']['text/plain']
        latex = app.user_ns['a']['text/latex']
    else:
        text = app.user_ns['a'][0]['text/plain']
        latex = app.user_ns['a'][0]['text/latex']
    assert text in ("{pi: 3.14, n_i: 3}",
                    u('{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}'),
                    "{n_i: 3, pi: 3.14}",
                    u('{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}'))
    assert latex == r'$$\left \{ n_{i} : 3, \quad \pi : 3.14\right \}$$'

    app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
    app.run_cell("init_printing(use_latex=True, print_builtin=False)")
    app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
    # Deal with API change starting at IPython 1.0
    if int(ipython.__version__.split(".")[0]) < 1:
        text = app.user_ns['a']['text/plain']
        raises(KeyError, lambda: app.user_ns['a']['text/latex'])
    else:
        text = app.user_ns['a'][0]['text/plain']
        raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
    # Note : Unicode of Python2 is equivalent to str in Python3. In Python 3 we have one
    # text type: str which holds Unicode data and two byte types bytes and bytearray.
    # Python 3.3.3 + IPython 0.13.2 gives: '{n_i: 3, pi: 3.14}'
    # Python 3.3.3 + IPython 1.1.0 gives: '{n_i: 3, pi: 3.14}'
    # Python 2.7.5 + IPython 1.1.0 gives: '{pi: 3.14, n_i: 3}'
    assert text in ("{pi: 3.14, n_i: 3}", "{n_i: 3, pi: 3.14}")
开发者ID:A-turing-machine,项目名称:sympy,代码行数:60,代码来源:test_ipythonprinting.py


示例7: test_anticommutator

def test_anticommutator():
    A = Operator('A')
    B = Operator('B')
    ac = AntiCommutator(A, B)
    ac_tall = AntiCommutator(A**2, B)
    assert str(ac) == '{A,B}'
    assert pretty(ac) == '{A,B}'
    assert upretty(ac) == u('{A,B}')
    assert latex(ac) == r'\left\{A,B\right\}'
    sT(ac, "AntiCommutator(Operator(Symbol('A')),Operator(Symbol('B')))")
    assert str(ac_tall) == '{A**2,B}'
    ascii_str = \
"""\
/ 2  \\\n\
<A ,B>\n\
\\    /\
"""
    ucode_str = \
u("""\
⎧ 2  ⎫\n\
⎨A ,B⎬\n\
⎩    ⎭\
""")
    assert pretty(ac_tall) == ascii_str
    assert upretty(ac_tall) == ucode_str
    assert latex(ac_tall) == r'\left\{\left(A\right)^{2},B\right\}'
    sT(ac_tall, "AntiCommutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
开发者ID:B-Rich,项目名称:sympy,代码行数:27,代码来源:test_printing.py


示例8: test_operator

def test_operator():
    a = Operator('A')
    b = Operator('B', Symbol('t'), S(1)/2)
    inv = a.inv()
    f = Function('f')
    x = symbols('x')
    d = DifferentialOperator(Derivative(f(x), x), f(x))
    op = OuterProduct(Ket(), Bra())
    assert str(a) == 'A'
    assert pretty(a) == 'A'
    assert upretty(a) == u('A')
    assert latex(a) == 'A'
    sT(a, "Operator(Symbol('A'))")
    assert str(inv) == 'A**(-1)'
    ascii_str = \
"""\
 -1\n\
A  \
"""
    ucode_str = \
u("""\
 -1\n\
A  \
""")
    assert pretty(inv) == ascii_str
    assert upretty(inv) == ucode_str
    assert latex(inv) == r'\left(A\right)^{-1}'
    sT(inv, "Pow(Operator(Symbol('A')), Integer(-1))")
    assert str(d) == 'DifferentialOperator(Derivative(f(x), x),f(x))'
    ascii_str = \
"""\
                    /d            \\\n\
DifferentialOperator|--(f(x)),f(x)|\n\
                    \dx           /\
"""
    ucode_str = \
u("""\
                    ⎛d            ⎞\n\
DifferentialOperator⎜──(f(x)),f(x)⎟\n\
                    ⎝dx           ⎠\
""")
    assert pretty(d) == ascii_str
    assert upretty(d) == ucode_str
    assert latex(d) == \
        r'DifferentialOperator\left(\frac{d}{d x} f{\left (x \right )},f{\left (x \right )}\right)'
    sT(d, "DifferentialOperator(Derivative(Function('f')(Symbol('x')), Symbol('x')),Function('f')(Symbol('x')))")
    assert str(b) == 'Operator(B,t,1/2)'
    assert pretty(b) == 'Operator(B,t,1/2)'
    assert upretty(b) == u('Operator(B,t,1/2)')
    assert latex(b) == r'Operator\left(B,t,\frac{1}{2}\right)'
    sT(b, "Operator(Symbol('B'),Symbol('t'),Rational(1, 2))")
    assert str(op) == '|psi><psi|'
    assert pretty(op) == '|psi><psi|'
    assert upretty(op) == u('❘ψ⟩⟨ψ❘')
    assert latex(op) == r'{\left|\psi\right\rangle }{\left\langle \psi\right|}'
    sT(op, "OuterProduct(Ket(Symbol('psi')),Bra(Symbol('psi')))")
开发者ID:B-Rich,项目名称:sympy,代码行数:56,代码来源:test_printing.py


示例9: test_vector_derivative_printing

def test_vector_derivative_printing():
    # First order
    v = omega.diff() * N.x
    assert unicode_vpretty(v) == u('ω̇ n_x')
    assert ascii_vpretty(v) == u("omega'(t) n_x")

    # Second order
    v = omega.diff().diff() * N.x

    assert v._latex() == r'\ddot{\omega}\mathbf{\hat{n}_x}'
    assert unicode_vpretty(v) == u('ω̈ n_x')
    assert ascii_vpretty(v) == u("omega''(t) n_x")

    # Third order
    v = omega.diff().diff().diff() * N.x

    assert v._latex() == r'\dddot{\omega}\mathbf{\hat{n}_x}'
    assert unicode_vpretty(v) == u('ω⃛ n_x')
    assert ascii_vpretty(v) == u("omega'''(t) n_x")

    # Fourth order
    v = omega.diff().diff().diff().diff() * N.x

    assert v._latex() == r'\ddddot{\omega}\mathbf{\hat{n}_x}'
    assert unicode_vpretty(v) == u('ω⃜ n_x')
    assert ascii_vpretty(v) == u("omega''''(t) n_x")

    # Fifth order
    v = omega.diff().diff().diff().diff().diff() * N.x

    assert v._latex() == r'\frac{d^{5}}{d t^{5}} \omega{\left(t \right)}\mathbf{\hat{n}_x}'
    assert unicode_vpretty(v) == u('  5\n d\n───(ω) n_x\n  5\ndt')
    assert ascii_vpretty(v) == '  5\n d\n---(omega) n_x\n  5\ndt'
开发者ID:gamechanger98,项目名称:sympy,代码行数:33,代码来源:test_printing.py


示例10: test_operator

def test_operator():
    a = Operator("A")
    b = Operator("B", Symbol("t"), S(1) / 2)
    inv = a.inv()
    f = Function("f")
    x = symbols("x")
    d = DifferentialOperator(Derivative(f(x), x), f(x))
    op = OuterProduct(Ket(), Bra())
    assert str(a) == "A"
    assert pretty(a) == "A"
    assert upretty(a) == u"A"
    assert latex(a) == "A"
    sT(a, "Operator(Symbol('A'))")
    assert str(inv) == "A**(-1)"
    ascii_str = """\
 -1\n\
A  \
"""
    ucode_str = u(
        """\
 -1\n\
A  \
"""
    )
    assert pretty(inv) == ascii_str
    assert upretty(inv) == ucode_str
    assert latex(inv) == r"A^{-1}"
    sT(inv, "Pow(Operator(Symbol('A')), Integer(-1))")
    assert str(d) == "DifferentialOperator(Derivative(f(x), x),f(x))"
    ascii_str = """\
                    /d            \\\n\
DifferentialOperator|--(f(x)),f(x)|\n\
                    \dx           /\
"""
    ucode_str = u(
        """\
                    ⎛d            ⎞\n\
DifferentialOperator⎜──(f(x)),f(x)⎟\n\
                    ⎝dx           ⎠\
"""
    )
    assert pretty(d) == ascii_str
    assert upretty(d) == ucode_str
    assert latex(d) == r"DifferentialOperator\left(\frac{d}{d x} f{\left (x \right )},f{\left (x \right )}\right)"
    sT(d, "DifferentialOperator(Derivative(Function('f')(Symbol('x')), Symbol('x')),Function('f')(Symbol('x')))")
    assert str(b) == "Operator(B,t,1/2)"
    assert pretty(b) == "Operator(B,t,1/2)"
    assert upretty(b) == u"Operator(B,t,1/2)"
    assert latex(b) == r"Operator\left(B,t,\frac{1}{2}\right)"
    sT(b, "Operator(Symbol('B'),Symbol('t'),Rational(1, 2))")
    assert str(op) == "|psi><psi|"
    assert pretty(op) == "|psi><psi|"
    assert upretty(op) == u"❘ψ⟩⟨ψ❘"
    assert latex(op) == r"{\left|\psi\right\rangle }{\left\langle \psi\right|}"
    sT(op, "OuterProduct(Ket(Symbol('psi')),Bra(Symbol('psi')))")
开发者ID:scopatz,项目名称:sympy,代码行数:55,代码来源:test_printing.py


示例11: test_qubit

def test_qubit():
    q1 = Qubit('0101')
    q2 = IntQubit(8)
    assert str(q1) == '|0101>'
    assert pretty(q1) == '|0101>'
    assert upretty(q1) == u('❘0101⟩')
    assert latex(q1) == r'{\left|0101\right\rangle }'
    sT(q1, "Qubit(Integer(0),Integer(1),Integer(0),Integer(1))")
    assert str(q2) == '|8>'
    assert pretty(q2) == '|8>'
    assert upretty(q2) == u('❘8⟩')
    assert latex(q2) == r'{\left|8\right\rangle }'
    sT(q2, "IntQubit(8)")
开发者ID:B-Rich,项目名称:sympy,代码行数:13,代码来源:test_printing.py


示例12: test_upretty_sub_super

def test_upretty_sub_super():
    assert upretty( Symbol('beta_1_2') ) == u('β₁ ₂')
    assert upretty( Symbol('beta^1^2') ) == u('β¹ ²')
    assert upretty( Symbol('beta_1^2') ) == u('β²₁')
    assert upretty( Symbol('beta_10_20') ) == u('β₁₀ ₂₀')
    assert upretty( Symbol('beta_ax_gamma^i') ) == u('βⁱₐₓ ᵧ')
    assert upretty( Symbol("F^1^2_3_4") ) == u('F¹ ²₃ ₄')
    assert upretty( Symbol("F_1_2^3^4") ) == u('F³ ⁴₁ ₂')
    assert upretty( Symbol("F_1_2_3_4") ) == u('F₁ ₂ ₃ ₄')
    assert upretty( Symbol("F^1^2^3^4") ) == u('F¹ ² ³ ⁴')
开发者ID:sumitbh250,项目名称:sympy,代码行数:10,代码来源:test_pretty.py


示例13: test_dyadic_pretty_print

def test_dyadic_pretty_print():

    expected = u("""\
 2
a  n_x⊗n_y + b n_y⊗n_y + c⋅sin(α) n_z⊗n_y\
""")
    result = y._pretty().render()

    assert expected == result

    expected = u('α n_x⊗n_x + sin(ω) n_y⊗n_z + α⋅β n_z⊗n_x')
    result = x._pretty().render()

    assert expected == result
开发者ID:HuibinLin,项目名称:sympy,代码行数:14,代码来源:test_printing.py


示例14: test_print_builtin_option

def test_print_builtin_option():
    # Initialize and setup IPython session
    app = init_ipython_session()
    app.run_cell("ip = get_ipython()")
    app.run_cell("inst = ip.instance()")
    app.run_cell("format = inst.display_formatter.format")
    app.run_cell("from sympy import Symbol")
    app.run_cell("from sympy import init_printing")

    app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
    # Deal with API change starting at IPython 1.0
    if int(ipython.__version__.split(".")[0]) < 1:
        text = app.user_ns['a']['text/plain']
        raises(KeyError, lambda: app.user_ns['a']['text/latex'])
    else:
        text = app.user_ns['a'][0]['text/plain']
        raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
    # Note : In Python 3 the text is unicode, but in 2 it is a string.
    assert text in ("{pi: 3.14, n_i: 3}", u('{n\u1d62: 3, \u03c0: 3.14}'))

    # If we enable the default printing, then the dictionary's should render
    # as a LaTeX version of the whole dict: ${\pi: 3.14, n_i: 3}$
    app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
    app.run_cell("init_printing(use_latex=True)")
    app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
    # Deal with API change starting at IPython 1.0
    if int(ipython.__version__.split(".")[0]) < 1:
        text = app.user_ns['a']['text/plain']
        latex = app.user_ns['a']['text/latex']
    else:
        text = app.user_ns['a'][0]['text/plain']
        latex = app.user_ns['a'][0]['text/latex']
    assert text == u('{n\u1d62: 3, \u03c0: 3.14}')
    assert latex == '$$\\begin{Bmatrix}n_{i} : 3, & \\pi : 3.14\\end{Bmatrix}$$'

    app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
    app.run_cell("init_printing(use_latex=True, print_builtin=False)")
    app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
    # Deal with API change starting at IPython 1.0
    if int(ipython.__version__.split(".")[0]) < 1:
        text = app.user_ns['a']['text/plain']
        raises(KeyError, lambda: app.user_ns['a']['text/latex'])
    else:
        text = app.user_ns['a'][0]['text/plain']
        raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
    # Note : In Python 3 the text is unicode, but in 2 it is a string.
    # Python 3.3.3 + IPython 0.13.2 gives: '{n_i: 3, pi: 3.14}'
    # Python 3.3.3 + IPython 1.1.0 gives: '{n_i: 3, pi: 3.14}'
    # Python 2.7.5 + IPython 1.1.0 gives: '{pi: 3.14, n_i: 3}'
    assert text in ("{pi: 3.14, n_i: 3}", "{n_i: 3, pi: 3.14}")
开发者ID:AALEKH,项目名称:sympy,代码行数:50,代码来源:test_ipythonprinting.py


示例15: render

 def render(self, *args, **kwargs):
     self = e
     ar = self.args  # just to shorten things
     if len(ar) == 0:
         return unicode(0)
     ol = []  # output list, to be concatenated to a string
     for i, v in enumerate(ar):
         for j in 0, 1, 2:
             # if the coef of the basis vector is 1, we skip the 1
             if ar[i][0][j] == 1:
                 ol.append(u(" + ") + ar[i][1].pretty_vecs[j])
             # if the coef of the basis vector is -1, we skip the 1
             elif ar[i][0][j] == -1:
                 ol.append(u(" - ") + ar[i][1].pretty_vecs[j])
             elif ar[i][0][j] != 0:
                 # If the basis vector coeff is not 1 or -1,
                 # we might wrap it in parentheses, for readability.
                 arg_str = (VectorPrettyPrinter().doprint(
                     ar[i][0][j]))
                 if isinstance(ar[i][0][j], Add):
                     arg_str = u("(%s)") % arg_str
                 if arg_str[0] == u("-"):
                     arg_str = arg_str[1:]
                     str_start = u(" - ")
                 else:
                     str_start = u(" + ")
                 ol.append(str_start + arg_str + '*' +
                           ar[i][1].pretty_vecs[j])
     outstr = u("").join(ol)
     if outstr.startswith(u(" + ")):
         outstr = outstr[3:]
     elif outstr.startswith(" "):
         outstr = outstr[1:]
     return outstr
开发者ID:Lmaths,项目名称:sympy,代码行数:34,代码来源:vector.py


示例16: render

            def render(self, *args, **kwargs):
                ar = e.args  # just to shorten things
                settings = printer._settings if printer else {}
                if printer:
                    use_unicode = printer._use_unicode
                else:
                    from sympy.printing.pretty.pretty_symbology import (
                        pretty_use_unicode)
                    use_unicode = pretty_use_unicode()
                mpp = printer if printer else VectorPrettyPrinter(settings)
                if len(ar) == 0:
                    return unicode(0)
                bar = u("\N{CIRCLED TIMES}") if use_unicode else "|"
                ol = []  # output list, to be concatenated to a string
                for i, v in enumerate(ar):
                    # if the coef of the dyadic is 1, we skip the 1
                    if ar[i][0] == 1:
                        ol.extend([u(" + "),
                                  mpp.doprint(ar[i][1]),
                                  bar,
                                  mpp.doprint(ar[i][2])])

                    # if the coef of the dyadic is -1, we skip the 1
                    elif ar[i][0] == -1:
                        ol.extend([u(" - "),
                                  mpp.doprint(ar[i][1]),
                                  bar,
                                  mpp.doprint(ar[i][2])])

                    # If the coefficient of the dyadic is not 1 or -1,
                    # we might wrap it in parentheses, for readability.
                    elif ar[i][0] != 0:
                        if isinstance(ar[i][0], Add):
                            arg_str = mpp._print(
                                ar[i][0]).parens()[0]
                        else:
                            arg_str = mpp.doprint(ar[i][0])
                        if arg_str.startswith(u("-")):
                            arg_str = arg_str[1:]
                            str_start = u(" - ")
                        else:
                            str_start = u(" + ")
                        ol.extend([str_start, arg_str, u(" "),
                                  mpp.doprint(ar[i][1]),
                                  bar,
                                  mpp.doprint(ar[i][2])])

                outstr = u("").join(ol)
                if outstr.startswith(u(" + ")):
                    outstr = outstr[3:]
                elif outstr.startswith(" "):
                    outstr = outstr[1:]
                return outstr
开发者ID:A-turing-machine,项目名称:sympy,代码行数:53,代码来源:dyadic.py


示例17: __new__

    def __new__(cls, name, index, system, pretty_str, latex_str):
        from sympy.vector.coordsysrect import CoordSysCartesian
        if isinstance(name, Symbol):
            name = name.name
        if isinstance(pretty_str, Symbol):
            pretty_str = pretty_str.name
        if isinstance(latex_str, Symbol):
            latex_str = latex_str.name

        index = _sympify(index)
        system = _sympify(system)
        obj = super(BaseScalar, cls).__new__(cls, Symbol(name), index, system,
                                             Symbol(pretty_str),
                                             Symbol(latex_str))
        if not isinstance(system, CoordSysCartesian):
            raise TypeError("system should be a CoordSysCartesian")
        if index not in range(0, 3):
            raise ValueError("Invalid index specified.")
        # The _id is used for equating purposes, and for hashing
        obj._id = (index, system)
        obj._name = obj.name = name
        obj._pretty_form = u(pretty_str)
        obj._latex_form = latex_str
        obj._system = system

        return obj
开发者ID:AStorus,项目名称:sympy,代码行数:26,代码来源:scalar.py


示例18: __new__

    def __new__(cls, name, index, system, pretty_str, latex_str):
        name = str(name)
        pretty_str = str(pretty_str)
        latex_str = str(latex_str)
        #Verify arguments
        if not index in range(0, 3):
            raise ValueError("index must be 0, 1 or 2")
        if not isinstance(system, CoordSysCartesian):
            raise TypeError("system should be a CoordSysCartesian")
        #Initialize an object
        obj = super(BaseVector, cls).__new__(cls, Symbol(name), S(index),
                                             system, Symbol(pretty_str),
                                             Symbol(latex_str))
        #Assign important attributes
        obj._base_instance = obj
        obj._components = {obj: S(1)}
        obj._measure_number = S(1)
        obj._name = name
        obj._pretty_form = u(pretty_str)
        obj._latex_form = latex_str
        obj._system = system

        assumptions = {}
        assumptions['commutative'] = True
        obj._assumptions = StdFactKB(assumptions)

        #This attr is used for re-expression to one of the systems
        #involved in the definition of the Vector. Applies to
        #VectorMul and VectorAdd too.
        obj._sys = system

        return obj
开发者ID:Davidjohnwilson,项目名称:sympy,代码行数:32,代码来源:vector.py


示例19: _print_contents_pretty

 def _print_contents_pretty(self, printer, *args):
     from sympy.printing.pretty.stringpict import prettyForm
     pform = printer._print(self.args[0], *args)
     if self.is_annihilation:
         return pform
     else:
         return pform**prettyForm(u('\u2020'))
开发者ID:B-Rich,项目名称:sympy,代码行数:7,代码来源:fermion.py


示例20: test_qexpr

def test_qexpr():
    q = QExpr('q')
    assert str(q) == 'q'
    assert pretty(q) == 'q'
    assert upretty(q) == u('q')
    assert latex(q) == r'q'
    sT(q, "QExpr(Symbol('q'))")
开发者ID:B-Rich,项目名称:sympy,代码行数:7,代码来源:test_printing.py



注:本文中的sympy.core.compatibility.u函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python compatibility.unicode函数代码示例发布时间:2022-05-27
下一篇:
Python compatibility.reduce函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap