Skip to contents

Symbols, numbers, and expressions

Creating symbols and numbers, constructing expressions, and converting between R and symbolic values.

Symbol() sym_var() sym_symbols()
Create symbols
Dummy() Wild()
Dummy and wild symbols
Function()
Undefined functions
Lambda() apply_lambda()
Lambda functions
Integer() Rational() Float()
Exact integers, rationals and floating point numbers
sym_pi sym_E sym_I oo zoo nan EulerGamma Catalan GoldenRatio TribonacciConstant S_Pi S_E S_I S_Infinity S_NegativeInfinity S_ComplexInfinity S_NaN S_Zero S_One S_Half S_NegativeOne S_true S_false S_EmptySet
Mathematical constants and special values
Tuple()
Tuples
Dict() dict_get() dict_keys() dict_values() dict_items()
Symbolic dictionaries
Eq() Ne() Lt() Le() Gt() Ge() lhs() rhs()
Symbolic equations and inequalities
Ops(<sym>) Math(<sym>) Summary(<sym>) Complex(<sym>)
Arithmetic, comparison and logic operators for symbolic expressions
Add() Mul() Pow() Equality() Unequality() StrictLessThan() LessThan() StrictGreaterThan() GreaterThan() Rel() Subs() nfloat() bottom_up() default_sort_key() comp() check_assumptions() failing_assumptions() sstrrepr() true false Relational() sym_ordered()
Core constructors and helpers
UnevaluatedExpr()
Expression that does not evaluate
Idx() IndexedBase() Indexed() get_indices() get_contraction_structure() format_contraction_structure()
Indexed objects
NDimArray() MutableDenseNDimArray() ImmutableDenseNDimArray() DenseNDimArray() SparseNDimArray() MutableSparseNDimArray() ImmutableSparseNDimArray() shape()
Array aliases and indexed objects
as_sym() S()
Convert R values to symbolic expressions
sympify() sym_from_call()
Parse a string into a symbolic expression
as.numeric(<sym>) as.double(<sym>) as.complex(<sym>)
Convert a numeric expression to an R value
as_bigq() as_bigz()
Exact value of a symbolic integer or rational as gmp big number
is_sym()
Test whether an object is a symbolic expression
ff() ln() E1() Li() erf2() Id() LeviCivita() Eijk() chebyshevt_root() chebyshevu_root() transpose() adjoint() sym_rf()
Function aliases and small special functions
SympifyError() PoleError() PrecisionExhausted() ArgumentIndexError() GeometryError() MatrixError() ShapeError() NonSquareMatrixError() NonInvertibleMatrixError() NonPositiveDefiniteMatrixError() BasePolynomialError() ExactQuotientFailed() PolynomialDivisionFailed() OperationNotSupported() HeuristicGCDFailed() ModularGCDFailed() HomomorphismFailed() IsomorphismFailed() ExtraneousFactors() EvaluationFailed() RefinementFailed() CoercionFailed() NotInvertible() NotReversible() NotAlgebraic() DomainError() PolynomialError() UnificationFailed() UnsolvableFactorError() GeneratorsError() GeneratorsNeeded() ComputationFailed() UnivariatePolynomialError() MultivariatePolynomialError() PolificationFailed() OptionError() FlagError() DMError() DMBadInputError() DMDomainError() DMFormatError() DMRankError() DMShapeError() DMNotAField() DMNonInvertibleMatrixError() DMNonSquareMatrixError() DMValueError() QuantumError() HilbertSpaceError() ClosureFailure() StructureError() MissingUnityError() SMTLibSyntaxError() UnknownSMTLibCommandError() UnknownSMTLibOperatorError()
SymPy exceptions
sympy_seed()
Seed SymPy's random generator
init_printing() init_session() interactive_traversal()
Interactive sessions
polarify() sym_prod() sym_reshape() parallel_poly_from_expr() sqf_norm() gff() ilex() igrlex() igrevlex() carmichael
Small helpers
filldedent() capture() threaded() xthreaded() public() memoize_property() timed()
Utility helpers

Inspecting and transforming expressions

Structure, traversal, substitution, pattern matching, and rewriting.

sym_type()
Type of a symbolic expression
sym_args()
Arguments of a symbolic expression
sym_name()
Name of a symbol or function head
atoms()
Atoms of an expression
has()
Test whether an expression contains a subexpression
free_symbols()
Free symbols of an expression
preorder_traversal() postorder_traversal()
Preorder and postorder traversal
count_ops()
Count operations in an expression
subs() xreplace()
Substitute values or expressions
doit()
Evaluate unevaluated objects
rewrite()
Rewrite an expression in terms of other functions
sym_match() sym_replace()
Pattern matching
WildFunction()
Wild functions
unify_compound() unify_variable() unify_condvariable() unify_core() unify() rewriterule()
Unification
strat_identity() strat_seq() exhaust() memoize() condition() chain() strat_debug() null_safe() tryit() do_one() strat_switch() minimize() basic_fns expr_fns rl rm_id() unpack() glom() distribute() rebuild() strat_new() traverse canon() typed() branch treeapply() greedy() allresults() brute()
Strategies
branch_identity() branch_exhaust() onaction() branch_debug() multiplex() branch_condition() sfilter() notempty() branch_do_one() branch_chain() yieldify() branch_canon() branch_top_down() branch_sall()
Branching strategies
EPath() epath()
Manipulate expressions using paths
add_primitive() extract_multiplicatively() extract_additively() as_coefficient() extract_branch_factor()
Extracting factors and terms
could_extract_minus_sign()
Whether a leading minus sign can be pulled out of an expression
as_content_primitive()
Content and primitive part

Assumptions

Assumptions attached to symbols and the predicate based assumptions system.

assumptions()
Assumptions attached to a symbol
is_positive() is_negative() is_zero() is_nonzero() is_nonnegative() is_nonpositive() is_real() is_complex() is_integer() is_rational() is_irrational() is_even() is_odd() is_prime_expr() is_finite() is_infinite() is_imaginary() is_commutative() is_algebraic() is_transcendental()
Assumption shortcuts
Q
Assumption predicates
ask_fact()
Query assumptions about an expression
AssumptionsContext() global_assumptions assuming()
Assumption contexts
ask()
Ask whether a proposition holds under assumptions
refine()
Simplify an expression under assumptions
satask()
Decide a proposition by satisfiability
lra_satask()
Decide a proposition with linear real arithmetic
Predicate() AppliedPredicate()
Define an assumption predicate
register_predicate()
Register an assumption handler
AssumptionsWrapper() is_extended_real() is_extended_nonnegative()
Query predicates of an expression under assumptions
common_assumptions()
Assumptions shared by expressions

Numerical evaluation

N() evalf()
Numerical evaluation
lambdify()
Turn an expression into an R function
nsimplify()
Find simple exact forms of numbers

Printing

Parsing

parse_smtlib()
Parse SMT-LIB
parse_expr()
Parse a string into an expression with SymPy's parser
function_exponentiation() split_symbols_custom() split_symbols() implicit_multiplication() implicit_application() implicit_multiplication_application() auto_symbol() lambda_notation() factorial_notation() convert_xor() repeated_decimals() auto_number() t_rationalize() convert_equals_signs() standard_transformations
Token transformations of parse_expr
parser_T()
Select parse_expr transformations by number
parse_latex()
Parse a LaTeX string into an expression
parse_latex_lark()
Parse LaTeX with the lark grammar
parse_latex_lark_all()
All the readings of an ambiguous LaTeX string
parse_mathematica() parse_mathematica_to_fullformlist()
Parse a Mathematica expression

Simplification

simplify()
Simplify an expression
expand() expand_mul() expand_multinomial() expand_log() expand_power_exp() expand_power_base() expand_trig() expand_complex() expand_func()
Expand an expression
factor_sym() factor_list() sqf_list() sqf() sqf_part() sym_factor()
Factor polynomials
gcd_terms() factor_terms()
Common factors of terms
collect() rcollect()
Collect terms
collect_const()
Collect common numeric factors
cancel()
Cancel common factors of a rational function
together()
Combine a sum of fractions
apart() apart_list() assemble_partfrac_list()
Partial fraction decomposition
fraction() numer() denom()
Numerator and denominator
denoms()
Denominators of an expression
trigsimp_groebner() futrig() trigsimp() trigsimp_old() exptrigsimp()
Trigonometric simplification
TR0() TR1() TR2() TR2i() TR3() TR4() TR5() TR6() TR7() TR8() TR9() TR10() TR10i() TR11() TR12() TR13() TRmorrie() TR12i() TR14() TR15() TR16() TR111() TR22() TRpower() fu() hyper_as_trig()
Fu trigonometric simplification
powsimp() powdenest() logcombine()
Combine powers
radsimp() rad_rationalize() split_surds() collect_sqrt() sqrtdenest()
Rationalize denominators and denest square roots
signsimp() posify()
Simplify signs
gammasimp() combsimp()
Simplify gamma functions and combinatorial expressions
besselsimp()
Simplify Bessel functions
kroneckersimp()
Simplify products of Kronecker deltas
hyperexpand()
Expand hypergeometric functions
nc_simplify()
Simplify a noncommutative expression
factor_nc()
Factoring with noncommutative symbols
distribute_or_over_and() piecewise_simplify() simplify_univariate()
Simplify a Piecewise expression
separatevars()
Separate variables
cse()
Common subexpression elimination
ratsimpmodprime()
Rational simplification modulo a prime ideal
collect_abs() inversecombine() ratsimp() sum_simplify() product_simplify()
Simplification helpers

Calculus

Integration and integral transforms

gauss_legendre() gauss_laguerre() gauss_hermite() gauss_gen_laguerre() gauss_chebyshev_t() gauss_chebyshev_u() gauss_jacobi() gauss_lobatto()
Gaussian quadrature
polytope_integrate() intpoly_strip() main_integrate3d() main_integrate() polygon_integrate() distance_to_side() lineseg_integrate() integration_reduction() left_integral2D() integration_reduction_dynamic() left_integral3D() gradient_terms() hyperplane_parameters() intpoly_cross_product() best_origin() intpoly_decompose() point_sort() intpoly_norm() intpoly_intersection() is_vertex()
Integration over polytopes
Integral() sym_integrate()
Integrate an expression
integral_as_sum() principal_value()
Riemann sums and principal values of integrals
integral_transform()
Change of variables in an integral
ratint() ratint_ratpart() ratint_logpart() log_to_atan() log_to_real()
Integration of rational functions
heurisch() heurisch_wrapper()
The heuristic Risch algorithm
risch_integrate()
The Risch algorithm
meijerint_indefinite() meijerint_definite() meijerint_inversion()
Integration by Meijer G functions
integral_steps() manualintegrate()
Integration by the manual (step-by-step) method
line_integrate()
Line integrals
expand_dirac_delta() laplace_transform() inverse_laplace_transform()
Laplace transforms
fourier_transform() inverse_fourier_transform() sine_transform() inverse_sine_transform() cosine_transform() inverse_cosine_transform() hankel_transform() inverse_hankel_transform()
Fourier, sine, cosine and Hankel transforms
mellin_transform() inverse_mellin_transform()
Mellin transforms
LaplaceTransform() InverseLaplaceTransform() FourierTransform() InverseFourierTransform() MellinTransform() InverseMellinTransform() SineTransform() InverseSineTransform() CosineTransform() InverseCosineTransform() HankelTransform() InverseHankelTransform()
Unevaluated integral transforms
laplace_correspondence() laplace_initial_conds() singularityintegrate()
Laplace helpers and singularity function integration

Sequences and series objects

Solvers

domain_check()
Check that a point is in the domain of a function
invert_real() invert_complex()
Invert real and complex valued functions
linear_coeffs()
Coefficients of a linear expression
linear_eq_to_matrix()
Matrix form of a linear system
nonlinsolve()
Solve a system of nonlinear equations as a set
solve_decomposition()
Solve a composite equation by decomposition
solvify()
Solve an equation as a list, as solve() would
lpmin() lpmax() linprog() show_linprog()
Linear programming
solve(<sym>) solve(<character>) solve(<Poly>) solve(<list>)
Solve equations
solveset() solveset_real() solveset_complex()
Solve an equation or inequality as a set
linsolve()
Solve a linear system as a set
decompogen() homogeneous_order() solve_linear_system_LU() solve_triangulated() factor_system()
More equation solvers
substitution()
Solve a system of equations by substitution
solve_linear_system() solve_linear() checksol() solve_undetermined_coeffs() solve_poly_system() det_quick() inv_quick()
Solver helpers
nsolve()
Numerical solution of equations
solve_poly_inequality() solve_poly_inequalities() solve_rational_inequalities() reduce_rational_inequalities() reduce_abs_inequality() reduce_abs_inequalities() reduce_inequalities()
Inequalities in one real variable
unrad()
Remove radicals from an equation
constantsimp() constant_renumber()
Simplify arbitrary constants in an ODE solution
solve_univariate_inequality()
Solve a univariate inequality
not_empty_in()
Where an intersection with a finite set is not empty
rsolve()
Solve linear recurrences
rsolve_poly() rsolve_ratio() rsolve_hyper()
Building blocks of the recurrence solver
dsolve()
Solve ordinary differential equations
canonical_odes()
Canonical form of a system of ODEs
checkinfsol()
Check infinitesimals of an ODE
checkodesol()
Check solutions of ODEs
checksysodesol()
Check solutions of systems of ODEs
classify_ode()
Classify an ordinary differential equation
classify_sysode()
Classify a system of ODEs
infinitesimals()
Infinitesimals of a first order ODE
linear_ode_to_matrix()
Matrix form of a system of linear ODEs
linodesolve()
Solve a system of first order linear ODEs
matrix_exp_jordan_form()
Matrix exponential of a constant matrix times t
ode_order()
Order of a differential equation
classify_pde() pdsolve() checkpdesol() pde_separate() pde_separate_add() pde_separate_mul()
First order partial differential equations
diophantine() classify_diop() diop_solve()
Diophantine equations

Polynomials

bernoulli_poly() bernoulli_c_poly() genocchi_poly() euler_poly() andre_poly()
Appell sequences
gcdex_steps()
Steps of the extended Euclidean algorithm
Poly() as_expr()
Polynomial objects
`$`(<Poly>)
Methods of Poly objects
PurePoly() GroebnerBasis() rootof() RootOf() ComplexRootOf() lex grlex grevlex monic() cofactors() half_gcdex() pexquo() all_roots() cyclotomic_poly() symmetric_poly() interpolating_poly() random_poly() itermonomials() viete() legendre_poly() chebyshevt_poly() chebyshevu_poly() hermite_poly() hermite_prob_poly() laguerre_poly() jacobi_poly() sym_poly()
Polynomial aliases and constructions
sym_decompose() gff_list() subresultants() sym_trunc() symmetrize() rational_interpolate() minimal_polynomial() minpoly() swinnerton_dyer_poly() nth_power_roots_poly() ground_roots() intervals() refine_root() hurwitz_conditions() schur_conditions() poly_from_expr()
More polynomial functions
degree() total_degree() degree_list() LC() LM() LT() coeffs() monoms() poly_terms() all_coeffs() coeff()
Degrees and coefficients of polynomials
div() quo() rem() exquo() pdiv() prem() pquo() reduced()
Polynomial division
gcd() gcd_list() lcm_list() gcdex() invert() sym_lcm()
Greatest common divisor and least common multiple
primitive() content() terms_gcd()
Content and primitive part
factor_sym() factor_list() sqf_list() sqf() sqf_part() sym_factor()
Factor polynomials
resultant() discriminant()
Resultant and discriminant
groebner() is_zero_dimensional()
Groebner bases
compose() horner() interpolate()
Polynomial composition, Horner form and interpolation
roots()
Roots of a polynomial
nroots() real_roots() sturm() count_roots()
Numerical and real roots
CRootOf()
Indexed complex roots of polynomials
RootSum()
Sums over the roots of a polynomial
is_polynomial()
Is an expression a polynomial?
Monomial() format(<sym_monomial>) print(<sym_monomial>) Ops(<sym_monomial>)
Monomials
binomial_coefficients() binomial_coefficients_list() multinomial_coefficients() multinomial_coefficients_iterator()
Binomial and multinomial coefficients
nP() nC() nD()
Permutations, combinations and derangements
gosper_normal() gosper_term()
Gosper's algorithm helpers
Options()
Polynomial options
ZZ() QQ() RR() CC() EX() EXRAW() ZZ_I() QQ_I() GF() FF() poly_ring() frac_field() algebraic_field() CyclotomicField() Domain() IntegerRing() RationalField() RealField() ComplexField() ExpressionDomain() ExpressionRawDomain() FiniteField() PolynomialRing() FractionField() AlgebraicField() PythonIntegerRing() GMPYIntegerRing() ZZ_python() ZZ_gmpy() GMPYRationalField() QQ_python() QQ_gmpy() PythonFiniteField() GMPYFiniteField() FF_python() FF_gmpy() PythonRational() PythonRationalField() GMPYRational() PythonInteger() GMPYInteger() SymPyInteger() SymPyRational() SymPyReal() PythonReal() PythonComplex() to_sympy() from_sympy()
Polynomial domains
construct_domain()
Constructing the minimal domain
format(<sym_ring>) print(<sym_ring>) format(<sym_ring_element>) print(<sym_ring_element>) Ops(<sym_ring_element>) chooseOpsMethod(<sym_ring_element>) ring() xring() vring() sring() field() xfield() vfield() sfield()
Sparse polynomial rings and rational function fields
galois_group()
Galois group of a polynomial
tschirnhausen_transformation()
Tschirnhausen transformation of a polynomial

Algebraic number theory

Polynomial domains and DomainMatrix

Fraction fields, power series rings, solvable quintics and the DomainMatrix layer.

Matrices and linear algebra

hadamard_product() hadamard_power()
Hadamard (elementwise) products and powers
kronecker_product() combine_kronecker()
Kronecker products of matrices
CompanionMatrix() LofLU() UofLU() LofCholesky() UofCholesky() QofQR() RofQR() EigenVectors() EigenValues() UofSVD() SofSVD() VofSVD() mat_lu() mat_qr() mat_eig() mat_svd() DFT() IDFT()
Structured matrix expressions
MatrixUnit()
Matrix unit
GenericIdentity() GenericZeroMatrix()
Generic identity and zero matrices
MatrixSet() matrix_set_contains()
The set of matrices of a shape with entries in a set
ElementwiseApplyFunction()
Elementwise application of a function to a matrix expression
dotprodsimp()
Simplify a sum of products
Matrix() zeros() ones() eye() diag_matrix() `%^%`
Symbolic matrices
sym_diag() sym_trace() banded() rot_givens() SparseMatrix() MutableSparseMatrix() ImmutableSparseMatrix()
Matrix constructors
rot_axis1() rot_axis2() rot_axis3() rot_ccw_axis1() rot_ccw_axis2() rot_ccw_axis3() jordan_cell() casoratian() randMatrix() symarray() permanent() per() matrix_multiply_elementwise() ImmutableMatrix() MutableMatrix() MutableDenseMatrix() ImmutableDenseMatrix() as_immutable() as_mutable() todok() row_list() col_list() RL() CL() nnz()
Matrix constructions
dot() cross() norm_matrix() applyfunc() is_square() is_symmetric() is_zero_matrix() vec() pinv()
Matrix utilities
inverse() solve(<symmatrix>) rref() rank_matrix() nullspace() columnspace() rowspace() minor() cofactor() cofactor_matrix() adjugate() trace_matrix() sym_det()
Determinant, inverse, trace and friends
charpoly() eigenvals() eigenvects() is_diagonalizable() diagonalize()
Characteristic polynomial, eigenvalues and eigenvectors
is_positive_definite() is_positive_semidefinite() is_negative_definite() is_negative_semidefinite() is_indefinite()
Definiteness of a matrix
left_eigenvects() singular_values()
Left eigenvectors and singular values
jordan_form()
Jordan normal form
LUdecomposition() GramSchmidt() QRdecomposition() cholesky() LDLdecomposition()
Matrix decompositions
LUdecomposition_Simple() LUdecompositionFF() rank_decomposition() singular_value_decomposition() upper_hessenberg_decomposition() bidiagonal_decomposition() bidiagonalize()
More matrix decompositions
matrix_pow()
Power of a square matrix
matrix_log() analytic_func()
Matrix logarithm and analytic functions of a matrix
jordan_block() companion() wilkinson() get_diag_blocks()
Special matrices
echelon_form() rref_rhs()
Echelon forms
row_insert() col_insert() row_del() col_del() row_join() col_join() extract() permute() permute_rows() permute_cols() elementary_row_op() elementary_col_op() row_swap() col_swap() diagonal() upper_triangular() lower_triangular() vech() rot90() mat_row() mat_col() tolist() matrix_values() multiply_elementwise()
Row and column operations
minor_submatrix()
Minor submatrix
is_upper() is_lower() is_upper_hessenberg() is_lower_hessenberg() is_diagonal() is_hermitian() is_anti_symmetric() is_weakly_diagonally_dominant() is_strongly_diagonally_dominant() is_Identity() is_symbolic() is_echelon()
Structural tests of a matrix
inverse_GE() inverse_LU() inverse_ADJ() inverse_CH() inverse_LDL() inverse_QR() inverse_BLOCK()
Inverse by a named method
diagonal_solve() lower_triangular_solve() upper_triangular_solve() cholesky_solve() LDLsolve() LUsolve() QRsolve() gauss_jordan_solve() pinv_solve() cramer_solve() matrix_solve() solve_least_squares()
Linear solvers of a matrix
condition_number()
Condition number of a matrix
connected_components_decomposition() strongly_connected_components_decomposition()
Block decompositions from the graph of a matrix
normalized_vector() print_nonzero()
Normalized vector and nonzero pattern
hermite_normal_form() invariant_factors() smith_normal_form()
Hermite and Smith normal forms
smith_normal_decomp() is_smith_normal_form()
Smith normal form decomposition and test
matrix_exp()
Matrix exponential
jacobian() hessian() gradient() wronskian()
Jacobian, Hessian, gradient and Wronskian
MatrixSymbol() Identity() ZeroMatrix() OneMatrix() mat_shape() MatMul() MatAdd() MatPow() Transpose() Inverse() Adjoint() Trace() Determinant() Permanent() HadamardProduct() HadamardPower() KroneckerProduct() MatrixElement() FunctionMatrix() DiagMatrix() diagonalize_vector() DiagonalOf() DiagonalMatrix() PermutationMatrix() MatrixPermute() DotProduct() MatrixSlice() blockcut() BlockMatrix() BlockDiagMatrix() block_collapse() matrix_symbols() as_explicit()
Matrix expressions

Number theory

egypt_harmonic()
Harmonic prefix of an Egyptian fraction
isprime() is_gaussian_prime() is_fermat_pseudoprime() is_euler_pseudoprime() is_euler_jacobi_pseudoprime() mr() is_lucas_prp() is_strong_lucas_prp() is_extra_strong_lucas_prp() proth_test() is_mersenne_prime()
Primality tests
prime() nextprime() prevprime() primerange() randprime() primorial() cycle_length() composite() compositepi()
Generating primes
Sieve() sieve
Sieve of Eratosthenes
factorint() factorrat() primefactors()
Integer factorization
FactorCache() factor_cache
Cache of prime factors
pollard_rho() pollard_pm1()
Pollard's rho and p - 1 factoring
ecm()
Lenstra's elliptic curve factoring
qs_factor() qs()
Quadratic sieve
perfect_power()
Perfect powers
multiplicity() multiplicity_in_factorial()
Multiplicities of factors
smoothness() smoothness_p()
Smoothness of an integer
divisors() proper_divisors() divisor_count() proper_divisor_count() udivisors() udivisor_count() antidivisors() antidivisor_count()
Divisors
totient() reduced_totient() divisor_sigma() udivisor_sigma() primenu() primeomega() mobius() legendre_symbol() jacobi_symbol() kronecker_symbol() primepi()
Number theoretic functions
mersenne_prime_exponent() is_perfect() abundance() is_abundant() is_deficient() is_amicable() is_carmichael() find_carmichael_numbers_in_range() find_first_n_carmichaels()
Perfect, abundant, deficient, amicable and Carmichael numbers
core() dra() drm()
Square free and other cores, and digital roots
igcd() ilcm() mod_inverse() integer_nthroot() integer_log() trailing() num_digits() arity()
Integer helpers
python_gcd() python_lcm() python_gcdex() gmpy_gcd() gmpy_lcm() gmpy_gcdex() gmpy_numer() gmpy_denom() gmpy_qdiv() sqrtrem()
Ground type integer functions
crt() crt1() crt2() symmetric_residue() solve_congruence()
Chinese remainder theorem
sqrt_mod() sqrt_mod_iter() quadratic_residues() is_quad_residue()
Square roots modulo n
is_nthpow_residue() nthroot_mod()
Power residues and n-th roots modulo m
quadratic_congruence() polynomial_congruence() binomial_mod()
Polynomial congruences
n_order() is_primitive_root() primitive_root()
Orders and primitive roots
discrete_log()
Discrete logarithm
continued_fraction() continued_fraction_periodic() continued_fraction_reduce() continued_fraction_iterator() continued_fraction_convergents()
Continued fractions
egyptian_fraction()
Egyptian fractions
npartitions()
Number of partitions
digits() count_digits() is_palindromic()
Digits of an integer
pi_hex_digits()
Hexadecimal digits of pi
extract_fundamental_discriminant()
Fundamental discriminant
EllipticCurve() EllipticCurvePoint() point_order()
Elliptic curves

Combinatorics and permutation groups

GrayCode() graycode_next() graycode_skip() generate_gray() graycode_unrank() random_bitstring() gray_to_bin() bin_to_gray() get_subset_from_bitstring() graycode_subsets()
Gray codes
IntegerPartition() as_dict() as_ferrers() prev_lex() next_lex() random_integer_partition()
Integer partitions
Partition() partition_sort_key() partition_from_rgs()
Set partitions
Prufer() prufer_next() prufer_prev() prufer_unrank() prufer_to_prufer() prufer_to_tree() prufer_edges()
Prufer sequences
RGS_generalized() RGS_enum() RGS_unrank() RGS_rank()
Restricted growth strings
Subset() subset_iterate_binary() subset_next_binary() subset_prev_binary() subset_next_lexicographic() subset_prev_lexicographic() subset_iterate_graycode() subset_next_gray() subset_prev_gray() subset_from_bitlist() bitlist_from_subset() subset_unrank_binary() subset_unrank_gray() subset_indices() ksubsets()
Subsets
character_table() dixon_character_table() character_table_sn() ct_tolist() ct_as_matrix() ct_shape() ct_zeta_order() ct_conjugacy_class_reps() CharacterTable()
Character tables of finite groups
symmetric() cyclic() alternating() dihedral()
Permutation group elements
Permutation() array_form() perm_size() perm_inverse() apply_perm() cyclic_form() full_cyclic_form() perm_list() perm_support() perm_rmul() perm_prod() perm_mul_inv() perm_commutes_with() perm_call() perm_transpositions() perm_from_sequence() perm_atoms() perm_next_lex() perm_unrank_nonlex() perm_rank_nonlex() perm_next_nonlex() perm_rank() perm_cardinality() perm_parity() perm_is_even() perm_is_odd() perm_is_singleton() perm_is_empty() perm_is_identity() perm_ascents() perm_descents() perm_max() perm_min() perm_inversions() perm_commutator() perm_signature() perm_sign() perm_order() perm_length() perm_cycle_structure() perm_cycles() perm_index() perm_runs() perm_inversion_vector() perm_rank_trotterjohnson() perm_unrank_trotterjohnson() perm_next_trotterjohnson() perm_precedence_matrix() perm_precedence_distance() perm_adjacency_matrix() perm_adjacency_distance() perm_positional_distance() perm_josephus() perm_from_inversion_vector() perm_random() unrank_lex() perm_resize()
Permutations
Cycle() cycle_mul() cycle_size() cycle_as_list()
Cycles
PermutationGroup() group_generators() group_degree() group_identity() random_pr() group_base() baseswap() basic_orbits() basic_stabilizers() basic_transversals() composition_series() coset_transversal() coset_table() group_center() centralizer() group_commutator() coset_factor() generator_product() coset_rank() coset_unrank() group_elements() derived_series() derived_subgroup() group_generate() generate_dimino() generate_schreier_sims() group_contains() is_perfect_group() is_abelian() abelian_invariants() is_elementary() is_alt_sym() is_nilpotent() is_normal() is_primitive() minimal_blocks() is_solvable() is_subgroup() is_polycyclic() is_transitive() is_trivial() lower_central_series() max_div() minimal_block() conjugacy_class() conjugacy_classes() molien() normal_closure() orbit() orbit_rep() orbit_transversal() orbits() group_order() group_index() is_symmetric_group() is_alternating_group() is_cyclic() is_dihedral() pointwise_stabilizer() make_perm() group_random() random_stab() schreier_sims() schreier_sims_incremental() schreier_sims_random() schreier_vector() stabilizer() strong_gens() subgroup() subgroup_search() transitivity_degree() sylow_subgroup() quotient_group() group_equals()
Permutation groups
groups_count() is_nilpotent_number() is_abelian_number() is_cyclic_number()
Numbers of groups of a given order
SchurNumber() schur_lower_bound() schur_partition()
Schur numbers and sum-free partitions
SymmetricGroup() AlternatingGroup() CyclicGroup() DihedralGroup() AbelianGroup() DirectProduct() RubikGroup() rubik_cube_generators() rubik()
Named permutation groups
Coset() is_left_coset() is_right_coset() coset_as_list() SymmetricPermutationGroup()
Cosets and the symmetric group of a degree
S1TransitiveSubgroups S2TransitiveSubgroups S3TransitiveSubgroups S4TransitiveSubgroups S5TransitiveSubgroups S6TransitiveSubgroups
Names of the transitive subgroups of S1 to S6
get_perm_group() four_group() M20() S3_in_S6() A4_in_S6() S4m() S4p() A4xC2() S4xC2() G18() G36m() G36p() G72() PSL2F5() PGL2F5()
Permutation group of a named transitive subgroup
perm_af_direct_product()
Direct products of permutation generators
perm_group_presentation()
Presentation of a permutation group
orbit_homomorphism() block_homomorphism() hom_image() hom_kernel() hom_apply() hom_invert()
Homomorphisms of permutation groups
PolycyclicGroup() perm_polycyclic_group() pc_is_prime_order() pc_length() Collector() pc_presentation() minimal_uncollected_subword() pc_relations() collected_word() exponent_vector() pc_depth() leading_exponent() induced_pcgs() constructive_membership_test()
Polycyclic groups and collectors
Polyhedron() poly_corners() poly_faces() poly_pgroup() poly_size() poly_array_form() poly_cyclic_form() poly_edges() poly_rotate() poly_reset() poly_copy() tetrahedron() cube() octahedron() dodecahedron() icosahedron() polyhedron_faces()
Polyhedra
permutations() combinations() combinations_with_replacement() subsets() set_partitions() derangements() cartes() gray_code() nT() stirling()
Combinatorial generators
reshape_seq() multiset() ibin() common_prefix() common_suffix() strongly_connected_components() connected_components() rotate_left() rotate_right() least_rotation() minlex() multiset_combinations() multiset_permutations() ordered_partitions() binary_partitions() uniq() generate_bell() generate_involutions() multiset_derangements() generate_derangements() random_derangement() necklaces() bracelets() generate_oriented_forest() runs() sequence_partitions() sequence_partitions_empty() kbins() permute_signs() signed_permutations() roundrobin() partitions() multiset_partitions() flatten() unflatten() group() take() variations() sift() has_dups() has_variety() rotations() prefixes() postfixes() numbered_symbols() dict_merge() topological_sort()
Iterables
enum_all() enum_small() enum_large() enum_range() multiset_partitions_taocp() count_partitions()
Multiset partition enumeration
prufer_from_tree() tree_from_prufer()
Prufer sequences

Free groups and finitely presented groups

FreeGroup() free_group() xfree_group() fg_slice() fg_index() fp_contains() vfree_group()
Free groups
word_array_form() word_letter_form() word_letter_form_elm() word_ext_rep() word_len() is_identity_word() word_inverse() word_order() word_commutator() word_prod() word_dict() eliminate_words() eliminate_word() subword_index() is_dependent() is_independent() subword() contains_generators() cyclic_subword() cyclic_conjugates() is_cyclic_conjugate() number_syllables() exponent_syllable() generator_syllable() sub_syllables() substituted_word() is_cyclically_reduced() identity_cyclic_reduction() cyclic_reduction() power_of() exponent_sum() generator_count() word_index() word_contains()
Words in free groups
FpGroup() fp_group() xfp_group() fp_make_confluent() fp_reduce() fp_equals() fp_subgroup() fp_quotient() fp_coset_enumeration() fp_coset_table() fp_order() fp_most_frequent_generator() fp_random() fp_index() vfp_group()
Finitely presented groups
FpSubgroup() fps_contains() fps_order() fps_to_FpGroup()
Subgroups of finitely presented and free groups
fp_str()
Python style string of a group theory object
fp_to_perm_group() fp_derived_series() fp_lower_central_series() fp_center() fp_derived_subgroup() fp_centralizer() fp_normal_closure() fp_is_abelian() fp_is_nilpotent() fp_is_solvable() fp_elements() fp_is_cyclic() fp_abelian_invariants() fp_composition_series()
Permutation group methods of finitely presented groups
CosetTable() ct_omega() ct_n() ct_A() ct_copy() ct_is_complete() ct_define() ct_define_c() ct_scan_c() ct_coincidence_c() ct_scan() ct_scan_check() ct_merge() ct_rep() ct_coincidence() ct_scan_and_fill() ct_scan_and_fill_c() ct_look_ahead() ct_process_deductions() ct_process_deductions_check() ct_switch() ct_standardize() ct_compress() ct_conjugates() ct_coset_representative() ct_modified_define() ct_modified_scan() ct_modified_scan_and_fill() ct_modified_merge() ct_modified_rep() ct_modified_coincidence() coset_enumeration_r() modified_coset_enumeration_r() coset_enumeration_c()
Coset tables and coset enumeration
coset_table_options()
Coset table options
transversal2coset()
Coset representatives from transversals
low_index_subgroups() first_in_class()
Low index subgroups
reidemeister_presentation()
Reidemeister Schreier presentations
simplify_presentation() elimination_technique_1() elimination_technique_2()
Simplifying presentations
RewritingSystem() fp_rewriting_system() rws_rules() rws_set_max() rws_is_confluent() rws_add_rule() rws_make_confluent() rws_reduce() rws_reduce_using_automaton()
Rewriting systems for finitely presented groups
GroupHomomorphism() hom_images() hom_is_injective() hom_is_surjective() hom_is_isomorphism() hom_is_trivial() hom_factor() hom_compose() hom_restrict_to() hom_invert_subgroup() homomorphism() group_isomorphism() is_isomorphic()
Group homomorphisms

Logic

Xnor() Exclusive()
Xnor and Exclusive
dimacs_load() dimacs_load_file() load_file()
Read DIMACS CNF
distribute_and_over_or() distribute_xor_over_and()
Distribution laws
dpll_satisfiable() dpll() find_pure_symbol() find_unit_clause() unit_propagate() to_int_repr() pl_true_int_repr() unit_propagate_int_repr() find_pure_symbol_int_repr() find_unit_clause_int_repr() dpll_int_repr()
The DPLL algorithm
entails() KB() PropKB()
Entailment and knowledge bases
gateinputcount()
Number of gate inputs
literal_symbol()
The symbol of a literal
pl_true()
Evaluate a proposition in a model
to_anf() is_anf() anf_coeffs() ANFform() bool_minterm() bool_maxterm() bool_monomial()
Algebraic normal form
And() Or() Not() Xor() Nand() Nor() Implies() Equivalent() ITE()
Boolean operators
eliminate_implications() to_nnf() to_cnf() to_dnf() is_nnf() is_cnf() is_dnf()
Eliminate implications and convert to normal forms
simplify_logic()
Simplify boolean expressions
SOPform() POSform()
Sum of products and product of sums forms
satisfiable() valid()
Satisfiability
bool_map()
Map variables between equivalent boolean expressions
truth_table()
Truth table of a boolean expression

Sets

Special functions

cot() sec() csc() acot() asec() acsc() coth() sech() csch() acoth() asech() acsch() sinc() Abs() re() im() conjugate() arg() frac() Heaviside() DiracDelta() KroneckerDelta() LambertW() Max() Min() root() cbrt() real_root() sym_atan2() sym_Mod()
Elementary and complex functions
loggamma() polygamma() digamma_sym() lowergamma() uppergamma() factorial2() subfactorial() RisingFactorial() FallingFactorial() bernoulli() fibonacci() lucas() tribonacci() catalan() bell() harmonic() euler() genocchi() partition() motzkin() erf() erfc() erfi() erfinv() erfcinv() Ei() li() Si() Ci() Shi() Chi() expint() fresnels() fresnelc() zeta() dirichlet_eta() polylog() lerchphi() besselj() bessely() besseli() besselk() hankel1() hankel2() jn() yn() airyai() airybi() airyaiprime() airybiprime() elliptic_k() elliptic_e() elliptic_f() elliptic_pi() legendre() assoc_legendre() chebyshevt() chebyshevu() hermite() hermite_prob() laguerre() assoc_laguerre() gegenbauer() jacobi() Ynm() sym_beta() sym_factorial() sym_binomial()
Special functions
Rem() andre() multigamma() stieltjes() riemann_xi() owens_t() erf2inv() marcumq() appellf1() hn1() hn2() jn_zeros() SingularityFunction() betainc() betainc_regularized() jtheta() jacobi_normalized() Ynm_c() Znm() mathieus() mathieuc() mathieusprime() mathieucprime() exp_polar() polar_lift() unpolarify() unbranched_argument() periodic_argument() principal_branch() piecewise_exclusive() hyper() meijerg()
More special functions
Piecewise() piecewise_fold()
Piecewise defined functions
bspline_basis() bspline_basis_set() interpolating_spline()
B-splines

Geometry

Point() Point2D() Point3D() point_x() point_y() point_z() ambient_dimension() affine_rank() is_collinear() are_collinear() is_concyclic() is_scalar_multiple() midpoint() origin() orthogonal_direction() project() taxicab_distance() canberra_distance() unit() geo_transform() direction_ratio() direction_cosine()
Points
Line() Line2D() Line3D() Ray() Ray2D() Ray3D() Segment() Segment2D() Segment3D() direction() smallest_angle_between() are_concurrent() perpendicular_line() parallel_line() perpendicular_segment() perpendicular_bisector() slope() geo_coefficients() xdirection() ydirection() zdirection() closing_angle() bisectors() bounds()
Lines, rays and segments
Ellipse() Circle() major() foci() focus_distance() eccentricity() circumference() periapsis() apoapsis() semilatus_rectum() encloses_point() is_tangent() tangent_lines() normal_lines() evolute() auxiliary_circle() director_circle() second_moment_of_area() polar_second_moment_of_area() section_modulus()
Ellipses and circles
Polygon() Triangle() RegularPolygon() angles() perimeter() first_moment_of_area() sides() cut_section() apothem() interior_angle() exterior_angle() rotation() spin() is_similar() is_equilateral() is_isosceles() is_scalene() is_right() altitudes() orthocenter() circumcenter() circumradius() circumcircle() incenter() inradius() incircle() exradii() excenters() medians() medial() nine_point_circle() eulerline()
Polygons and triangles
Plane() is_coplanar() parallel_plane() perpendicular_plane() projection_line()
Planes
Curve() Parabola() axis_of_symmetry() focal_length() p_parameter() vertex()
Curves and parabolas
Ops(<GeoEntity>)
Operators on geometric entities
distance() intersection() area() centroid() geo_length() equation() line_equation() circle_equation() projection() angle_between() is_parallel() is_perpendicular() normal_vector() arbitrary_point() parameter_value() plot_interval() random_point() encloses() equals() are_similar() are_coplanar() convex_hull() closest_points() farthest_points()
Measurements and relations of geometric entities
geo_rotation_matrix() geo_translation_matrix() geo_scale_matrix() geo_rotate() geo_scale() geo_reflect() translate()
Transformations of geometric entities
rad() deg()
Angle conversion

Vectors

CoordSys3D() BaseScalar() locate_new() orient_new() orient_new_axis() orient_new_body() orient_new_space() orient_new_quaternion() create_new()
Three dimensional coordinate systems
AxisOrienter() BodyOrienter() SpaceOrienter() QuaternionOrienter() orienter_rotation_matrix()
Orienters
lame_coefficients() transformation_to_parent() transformation_from_parent() transformation_from_parent_function() rotation_matrix() change_of_basis_matrix_from() position_wrt() express_coordinates() scalar_map()
Properties of coordinate systems
VectorAdd() VectorMul() VectorZero() DyadicAdd() DyadicMul() DyadicZero() BaseVector() BaseDyadic() measure_number()
Vectors and dyadics of a coordinate system
magnitude() normalize() outer_sym() vector_equals() to_matrix() separate()
Vector operations
express() matrix_to_vector() matrix_to_dyadic() orthogonalize() directional_derivative() scalar_potential_difference()
Express vectors, dyadics and scalars in a coordinate system
grad() divergence() curl() laplacian() is_conservative() is_solenoidal() scalar_potential()
Vector calculus in Cartesian coordinates
Del() del_gradient() del_dot() del_cross()
The del operator
Gradient() Divergence() Curl() Laplacian()
Unevaluated differential operators
Cross() Dot()
Unevaluated dot and cross products
ParametricRegion() parametric_region_list()
Parametric regions
ImplicitRegion() implicit_degree() conic_coeff() regular_point() singular_points() rational_parametrization()
Implicit regions
ParametricIntegral() vector_integrate()
Integrals of fields over regions

Arrays and tensors

ArraySymbol() ArrayElement() ZeroArray() OneArray() ArrayTensorProduct() ArrayAdd() PermuteDims() ArrayDiagonal() ArrayElementwiseApplyFunc() ArrayContraction() Reshape() ArraySum()
Array expressions
ArrayComprehension() ArrayComprehensionMap()
Array comprehensions
array_derive() matrix_derive() ArrayDerivative()
Derivatives of array and matrix expressions
collect_tensor_products()
Collect sums of tensor products
convert_indexed_to_array() convert_array_to_indexed()
Convert between indexed and array expressions
convert_matrix_to_array() convert_array_to_matrix()
Convert between matrix and array expressions
get_shape() get_ndim() get_rank()
Shape and rank of array and matrix expressions
nest_permutation()
Nest the permutation of a PermuteDims
Array() arr_get() tensorproduct() tensorcontraction() permutedims() derive_by_array() tensordiagonal()
N-dimensional symbolic arrays
TensorHead() tensor_heads()
Tensor heads
TensorIndexType() TensorIndex() tensor_indices() TensorSymmetry() TensorSymmetry.fully_symmetric() TensorSymmetry.direct_product() TensorSymmetry.riemann() TensorSymmetry.no_symmetry()
Tensor index types, indices and symmetries
canon_bp() contract_metric() contract_delta() substitute_indices() get_free_indices() get_dummy_indices() TensMul() TensAdd() tensor_mul() riemann_cyclic_replace() riemann_cyclic()
Tensor expressions
WildTensorIndex() WildTensorHead()
Wild tensors and tensor pattern matching
PartialDerivative() pd_expand() pd_perform_derivative()
Partial derivative of tensor expressions
replace_with_arrays()
Replace tensors by arrays
TensorManager
Commutation groups of tensors
bsgs_direct_product() get_symmetric_group_sgs() riemann_bsgs get_transversals() get_minimal_bsgs() tensor_gens() gens_products()
BSGS of tensor symmetries
canonicalize()
Canonicalize a tensor formed by component tensors
canonical_free()
Canonicalize a tensor with respect to its free indices
double_coset_can_rep()
Butler-Portugal canonical representative of a double coset
dummy_sgs()
Strong generators of the dummy index symmetry

Differential geometry, Lie algebras, quaternions, and categories

Manifold() Patch() CoordSystem() coord_symbols() transformation() cs_transform() jacobian_dg() jacobian_determinant() point() point_to_coords() base_scalar() base_scalars() base_vector() base_vectors() base_oneform() base_oneforms() Differential() TensorProduct() WedgeProduct() Commutator() LieDerivative() BaseCovarDerivativeOp() CovarDerivativeOp() rcall() contravariant_order() covariant_order() vectors_in_basis() twoform_to_matrix() metric_to_Christoffel_1st() metric_to_Christoffel_2nd() metric_to_Riemann_components() metric_to_Ricci_components() intcurve_series() intcurve_diffequ() diffgeom_rn()
Differential geometry
CartanType() cartan_rank() dimension() basic_root() simple_root() positive_roots() highest_root() cartan_matrix() basis() lie_algebra() dynkin_diagram() CartanMatrix() DynkinDiagram() RootSystem() simple_roots() root_space() add_simple_roots() add_as_roots() WeylGroup() generators() group_name() delete_doubles() matrix_form() element_order() coxeter_diagram()
Lie algebras
Quaternion() quat_conjugate() quat_norm() quat_inverse() quat_to_rotation_matrix()
Quaternions
Object() IdentityMorphism() NamedMorphism() morphism_domain() codomain() morphism_name() components() CompositeMorphism() flatten_morphism() Category() category_objects() commutative_diagrams() Diagram() premises() conclusions() diagram_objects() hom() is_subdiagram() subdiagram_from_objects() Morphism()
Categories
DiagramGrid() grid_get() ArrowStringDescription() XypicDiagramDrawer() xypic_draw_diagram() preview_diagram()
Drawing diagrams

Physical units

Physics vectors

Reference frames, vectors, dyadics and points from sympy.physics.vector.

ReferenceFrame()
Reference frames for classical mechanics
CoordinateSym()
Coordinate variables of a reference frame
PhysVector() PhysDyadic()
Vectors and dyadics of classical mechanics
ActuatorBase() PathwayBase() WrappingGeometryBase() BodyBase() LoadBase() MethodBase() BosonicBasis() Vector() Dyadic()
Abstract base classes of the physics modules
PhysPoint()
Points of classical mechanics
dynamicsymbols()
Dynamic symbols
time_derivative()
Time derivative in a reference frame
kinematic_equations()
Kinematic differential equations
get_motion_params()
Motion parameters from kinematic conditions
partial_velocity()
Partial velocities
mprint() msprint() mpprint() mlatex() mechanics_printing() vsprint() vsstrrepr() vprint() vlatex() VectorLatexPrinter() vpprint() init_vprinting()
Printing for classical mechanics

Mechanics

Bodies, loads, joints, pathways, actuators and equations of motion from sympy.physics.mechanics.

Particle() RigidBody()
Particles and rigid bodies
Body()
Bodies of the deprecated joints framework
inertia() inertia_of_point_mass() Inertia() Inertia_from_inertia_scalars()
Inertia dyadics and the Inertia tuple
Force() Torque() gravity()
Loads: forces and torques
Joint() PinJoint() PrismaticJoint() CylindricalJoint() PlanarJoint() SphericalJoint() WeldJoint()
Joints between bodies
LinearPathway() ObstacleSetPathway() WrappingPathway()
Pathways of actuators
WrappingSphere() WrappingCylinder() WrappingCone()
Wrapping geometries
ForceActuator() LinearSpring() LinearDamper() TorqueActuator() TorqueActuator_at_pin_joint() DuffingSpring() CoulombKineticFriction()
Actuators
KanesMethod()
Kane's method
LagrangesMethod()
Lagrange's method
JointsMethod()
Equations of motion of a set of joints
Linearizer()
Linearizer of equations of motion
System() System_from_newtonian()
Multibody systems
SymbolicSystem()
Symbolic equations of motion
linear_momentum() angular_momentum() kinetic_energy() potential_energy() center_of_mass() Lagrangian()
Momentum, energy and the Lagrangian of a system of bodies
find_dynamicsymbols()
Dynamic symbols of an expression
msubs()
Substitution for mechanics expressions
multi_mass_spring_damper() n_link_pendulum_on_cart()
Example multibody models
`$`(<physics_obj>) `$<-`(<physics_obj>)
Attribute access for classical mechanics objects

Biomechanics

Activation dynamics, characteristic curves and musculotendon models from sympy.physics.biomechanics.

Optics

sympy.physics.optics: Gaussian beams, ray transfer matrices, media, polarization and waves.

Control systems

sympy.physics.control: transfer functions, state space models, interconnections, Routh-Hurwitz and response data.

Continuum mechanics

sympy.physics.continuum_mechanics: beams, columns, trusses, cables and arches.

Beam() Beam3D()
Beams
Column()
Columns under axial loads
Truss()
Trusses
Cable()
Cables
Arch()
Arches

Other physics

Hydrogen atom, harmonic oscillators, particle on a ring, Wigner symbols and physics matrices.

hydrogen_R_nl() hydrogen_Y_lm() hydrogen_Z_lm() hydrogen_Psi_nlm() hydrogen_E_nl() hydrogen_E_nl_dirac()
The hydrogen atom
sho_R_nl() sho_E_nl()
The isotropic harmonic oscillator
qho_psi_n() qho_E_n() qho_coherent_state()
The one dimensional quantum harmonic oscillator
pring_wavefunction() pring_energy()
The particle on a ring
wigner_d_small() wigner_d()
Wigner small d and D matrices
dot_rot_grad_Ynm()
Dot product of rotational gradients of spherical harmonics
msigma() pat_matrix() mgamma() minkowski_tensor mdft()
Matrices of physics

Quantum mechanics

sympy.physics.quantum, secondquant, paulialgebra and hep.gamma_matrices.

AntiCommutator()
Anticommutators
Dagger()
Hermitian conjugate
HBar() hbar
Reduced Planck constant
InnerProduct()
Inner products
Tr()
Trace of a quantum expression
Wavefunction()
Wavefunctions
BosonOp() BosonFockKet() BosonFockBra() BosonCoherentKet() BosonCoherentBra()
Bosonic operators and states
XOp() YOp() ZOp() PxOp() XKet() XBra() PositionState3D() PositionKet3D() PositionBra3D() PxKet() PxBra() Px
Cartesian position and momentum
Wigner3j() CG() Wigner6j() Wigner9j() cg_simp()
Clebsch-Gordan coefficients and Wigner symbols as expressions
Mz() Mx() CreateOneQubitGate() CreateCGate() labeller()
Measurement gates and gate factories
circuit_plot() CircuitPlot()
Plot quantum circuits
kmp_table() find_subcircuit() replace_subcircuit() convert_to_symbolic_indices() convert_to_real_indices() random_reduce() random_insert()
Circuit utilities
combined_tensor_printing() tensor_product_simp()
Combined printing of tensor products
fidelity()
Density operators, entropy and fidelity
FermionOp() FermionFockKet() FermionFockBra()
Fermionic operators and states
LorentzIndex GammaMatrix() extract_type_tens() simplify_gamma_expression() simplify_gpgp() gamma_trace() kahane_simplify()
Gamma matrices
superposition_basis() OracleGate() WGate() grover_iteration() apply_grover()
Grover's search
HilbertSpace() ComplexSpace() L2() FockSpace() TensorProductHilbertSpace() DirectSumHilbertSpace() TensorPowerHilbertSpace() hs_contains()
Hilbert spaces
is_scalar_nonsparse_matrix() is_scalar_sparse_matrix() is_scalar_matrix() generate_gate_rules() generate_equivalent_ids() GateIdentity() is_degenerate() is_reducible() bfs_identity_search() random_identity_search()
Gate identities
m_values()
Spin quantum numbers
normalized()
Use normalized Hadamard gates
normal_ordered_form() normal_order()
Normal ordering of bosonic and fermionic operators
operators_to_state() state_to_operators()
Operators and their eigenstates
Pauli() evaluate_pauli_product()
Pauli algebra
SigmaX() SigmaY() SigmaZ() SigmaMinus() SigmaPlus() SigmaZKet() SigmaZBra() qsimplify_pauli()
Pauli operators
PIABHamiltonian() PIABKet() PIABBra()
Particle in a box
qapply()
Apply operators to states
Qasm() read_qasm() read_qasm_file()
QASM circuits
QFT() IQFT() RkGate() Rk()
Quantum Fourier transform
qattr() qcall() qisinstance() qclass()
Attributes and methods of quantum objects
Gate() CGate() CGateS() UGate() OneQubitGate() TwoQubitGate() IdentityGate() HadamardGate() XGate() YGate() ZGate() PhaseGate() TGate() X() Y() Z() Phase() CNotGate() CNOT() SwapGate() SWAP() CPHASE() represent_zbasis() gate_simp() gate_sort() random_circuit()
Quantum gates
matrix_tensor_product() matrix_eye() matrix_zeros() matrix_dagger() matrix_to_zero() sympy_to_numpy() to_numpy() numpy_to_sympy()
Matrix utilities of the quantum module
Operator() HermitianOperator() UnitaryOperator() IdentityOperator() OuterProduct() DifferentialOperator()
Quantum operators
QubitState() Qubit() QubitBra() IntQubit() IntQubitBra() matrix_to_qubit() matrix_to_density() qubit_to_matrix() measure_all() measure_partial() measure_partial_oneshot() measure_all_oneshot()
Qubits
QExpr() StateBase() KetBase() BraBase() State() Ket() Bra() TimeDepState() TimeDepKet() TimeDepBra() OrthogonalState() OrthogonalKet() OrthogonalBra()
Quantum states
represent() rep_innerproduct() rep_expectation() integrate_result() get_basis() enumerate_states()
Matrix representations
NO() contraction() evaluate_deltas() substitute_dummies() wicks() PermutationOperator() simplify_index_permutations()
Normal ordering, contractions and Wick's theorem
sq_Dagger() AntiSymmetricTensor() SqOperator() BosonicOperator() AnnihilateBoson() CreateBoson() B() Bd() FermionicOperator() AnnihilateFermion() CreateFermion() sym_F() Fd() FockState() BosonState() FermionState() FockStateKet() FockStateBra() FockStateBosonKet() FockStateBosonBra() FockStateFermionKet() FockStateFermionBra() BKet() BBra() FKet() FBra() apply_operators() sq_InnerProduct() matrix_rep() VarBosonicBasis() FixedBosonicBasis() sq_Commutator()
Second quantization
RaisingOp() LoweringOp() NumberOp() Hamiltonian() SHOKet() SHOBra()
One-dimensional harmonic oscillator
CMod() shor() getr() ratioize() period_find()
Shor's algorithm
JxOp() JyOp() JzOp() J2Op() JplusOp() JminusOp() Jx Jy Jz J2 Jplus Jminus Rotation() Rotation_D() Rotation_d() WignerD()
Spin operators, rotations and Wigner D functions
SpinState() JxKet() JxBra() JyKet() JyBra() JzKet() JzBra() CoupledSpinState() JxKetCoupled() JxBraCoupled() JyKetCoupled() JyBraCoupled() JzKetCoupled() JzBraCoupled() couple() uncouple()
Spin states
wigner_3j() clebsch_gordan() wigner_6j() racah() wigner_9j() gaunt() real_gaunt()
Wigner 3j, 6j and 9j symbols and related coefficients

Code generation

The sympy.codegen AST, code printers, rewriting and optimization, and utilities.codegen routines.

CuPyPrinter() JaxPrinter()
Array code printers
TensorflowPrinter() tensorflow_code() TorchPrinter() torch_code()
TensorFlow and PyTorch code printing
lambdarepr() NumExprPrinter() IntervalPrinter()
Lambda code printers
Token() BreakToken() ContinueToken() NoneToken() none break_ continue_ String() QuotedString() Comment() Node() Type() IntBaseType() SignedIntType() UnsignedIntType() FloatBaseType() FloatType() ComplexBaseType() ComplexType() intc intp int8 int16 int32 int64 uint8 uint16 uint32 uint64 float16 float32 float64 float80 float128 float256 complex64 complex128 untyped real sym_integer complex_ bool_ Attribute() value_const pointer_const Variable() Pointer() Element() Declaration() Assignment() AddAugmentedAssignment() SubAugmentedAssignment() MulAugmentedAssignment() DivAugmentedAssignment() ModAugmentedAssignment() aug_assign() CodeBlock() For() While() Scope() Stream() stdout_ stderr_ Print() FunctionPrototype() FunctionDefinition() Return() FunctionCall() KeywordFunctionCall() Raise() RuntimeError_()
Code generation abstract syntax tree
ast_attr() ast_kwargs() ast_func() ast_getitem() attr_params()
Fields of code generation nodes
type_from_expr() type_cast_nocheck() type_cast_check() variable_deduced() pointer_deduced() as_Declaration() from_FunctionDefinition() from_FunctionPrototype()
Codegen type helpers
DataType() get_default_datatype() InputArgument() OutputArgument() InOutArgument() Result()
Data types and arguments of code generation routines
codeblock_topological_sort() codeblock_cse()
CodeBlock methods
List() NumExprEvaluate() void restrict volatile static alignof() sizeof() CommaOperator() Label() goto() PreDecrement() PostDecrement() PreIncrement() PostIncrement() struct() c_union() using() constexpr
Codegen nodes for C, C++, Python and lists
pure elemental intent_in intent_out intent_inout allocatable Program() use_rename() fortran_use() Module() Subroutine() SubroutineCall() Do() ArrayConstructor() ImpliedDoLoop() Extent() assumed_extent fortran_dimension() assumed_size fortran_array() allocated() lbound() ubound() fortran_shape() size() fortran_reshape() bind_C() GoTo() FortranReturn() isign() dsign() cmplx() kind() fortran_merge() literal_sp() literal_dp() sum_() product_()
Fortran codegen nodes
logaddexp() logaddexp2() amin() amax() np_maximum() np_minimum() cosm1() powm1()
NumPy and SciPy codegen functions
sym_expm1() sym_log1p() exp2() sym_log2() fma() sym_log10() Sqrt() Cbrt() hypot() isnan() isinf()
C99 math functions
ReplaceOptim() sym_optimize() exp2_opt() sinc_opt1() sinc_opt2() sinc_opts log2_opt() log2const_opt() logsumexp_2terms_opt() FuncMinusOneOptim() expm1_opt() cosm1_opt() powm1_opt() log1p_opt() create_expand_pow_optimization() matinv_opt() logaddexp_opt() logaddexp2_opt() optims_c99 optims_numpy optims_scipy
Rewriting expressions for numerical evaluation
newtons_method() newtons_method_function()
Newton's method as an abstract syntax tree
SumApprox() SeriesApprox()
Approximations of sums and of functions
MatrixSolve()
Solve a linear system in generated code
StrPrinter() printer_doprint() C89CodePrinter() C99CodePrinter() C11CodePrinter() CXX98CodePrinter() CXX11CodePrinter() CXX17CodePrinter() FCodePrinter() JavascriptCodePrinter() JuliaCodePrinter() OctaveCodePrinter() PythonCodePrinter() MpmathPrinter() NumPyPrinter() SciPyPrinter() LambdaPrinter() RCodePrinter() RustCodePrinter()
Code printer objects
get_math_macros() cgdict_get()
C math macros
CCodeGen() C89CodeGen() C99CodeGen() FCodeGen() JuliaCodeGen() OctaveCodeGen() RustCodeGen() get_code_generator() codegen()
Code generators
Routine() make_routine()
Routines for code generation
render_as_source_file() py_render_as_module() f_render_as_module()
Source files and modules from abstract syntax trees
implemented_function()
Add a numerical implementation to an undefined function
lambdastr()
Python source of a lambda function

Statistics

DiscreteMarkovChain() ContinuousMarkovChain() TransitionMatrixOf() GeneratorMatrixOf() StochasticStateSpaceOf()
Markov chains
sample_stochastic_process()
Sample a stochastic process
sampling_density()
Sampling density
ContinuousDistributionHandmade() DiscreteDistributionHandmade() FiniteDistributionHandmade()
Handmade distributions
ExpectationMatrix() VarianceMatrix() CrossCovarianceMatrix()
Matrix expectation, variance and cross covariance
ContinuousRV() Arcsin() Benini() BetaRV() BetaNoncentral() BetaPrime() BoundedPareto() Cauchy() ChiRV() ChiNoncentral() ChiSquared() Dagum() Davis() Erlang() ExGaussian() Exponential() ExponentialPower() FDistribution() FisherZ() Frechet() GammaRV() GammaInverse() Gumbel() Gompertz() Kumaraswamy() Laplace() Levy() LogCauchy() Logistic() LogLogistic() LogitNormal() LogNormal() Lomax() Maxwell() Moyal() Nakagami() Normal() GaussianInverse() Wald() Pareto() PowerFunction() QuadraticU() RaisedCosine() Rayleigh() Reciprocal() ShiftedGompertz() SkewNormal() StudentT() Trapezoidal() Triangular() Uniform() UniformSum() VonMises() Weibull() WignerSemicircle()
Continuous random variables
DiscreteRV() FlorySchulz() Geometric() Hermite() Logarithmic() NegativeBinomial() Poisson() Skellam() YuleSimon() Zeta()
Discrete random variables
FiniteRV() DiscreteUniform() Die() Bernoulli() Coin() Binomial() BetaBinomial() Hypergeometric() Rademacher() IdealSoliton() RobustSoliton()
Finite random variables
random_symbols() is_random() pspace()
Random symbols in an expression
RandomSymbol()
Random symbols
RandomIndexedSymbol() BernoulliProcess() PoissonProcess() WienerProcess() GammaProcess() StochasticProcess() DiscreteTimeStochasticProcess() ContinuousTimeStochasticProcess()
Stochastic processes
E() expectation() P() probability() rv_density() Density() rv_cdf() characteristic_function() moment_generating_function() rv_quantile()
Expectation, probability and distribution functions
given() rs_swap() dependent() independent() where()
Conditional random expressions and events
marginal_distribution() JointRV() MultivariateNormal() MultivariateLaplace() MultivariateT() NormalGamma() MultivariateBeta() Dirichlet() MultivariateEwens() GeneralizedMultivariateLogGamma() GeneralizedMultivariateLogGammaOmega() Multinomial() NegativeMultinomial()
Joint random variables
moment() variance() standard_deviation() std() entropy() H() covariance() correlation() cmoment() smoment() skewness() kurtosis() factorial_moment() rv_median() coskewness()
Moments and summary statistics of random expressions
rv_sample()
Draw random samples
rv_attr() rv_getitem()
Attributes and items of stats objects
Probability() Expectation() Variance() Covariance() Moment() CentralMoment()
Unevaluated probability expressions
MatrixGamma() Wishart() MatrixNormal() MatrixStudentT()
Matrix distributions
GaussianEnsemble() GaussianUnitaryEnsemble() GaussianOrthogonalEnsemble() GaussianSymplecticEnsemble() CircularEnsemble() CircularUnitaryEnsemble() CircularOrthogonalEnsemble() CircularSymplecticEnsemble() joint_eigen_distribution() level_spacing_distribution() JointEigenDistribution() RandomMatrixSymbol()
Random matrix ensembles
variance_prop()
Propagation of variance

Discrete transforms and cryptography

Kinds, dispatch and evaluation control

Power series rings and interval arithmetic

power_series_ring() PowerSeriesRingRing() PowerSeriesRingField()
Power series rings
closure() interior() powerset() symmetric_difference()
Closure, interior and power set of a set
graph_certificate()
Certificate of a graph
interval() imin() imax() ceil() intervalMembership()
Interval arithmetic for plotting
AlgIntPowers() alg_int_power() `[[`(<AlgIntPowers>) coeff_search()
Powers of an algebraic integer, and a coefficient search

Printing, plotting and numeric helpers

pretty_symbol() xsym() hobj() vobj() center_pad() center() annotated() greek_unicode sup
Pretty printing symbology
preview()
Render an expression with LaTeX
DeferredVector() `[`(<DeferredVector>)
Deferred vectors for lambdify
list2numpy() matrix2numpy()
Lists and matrices as R arrays
vectorize()
Vectorize a function over nested lists
sample_iter()
Draw samples as expressions
allhints
ODE solver hints
BaseScalarField() BaseVectorField() CoordinateSymbol() R2 R2_origin relations_2d R2_r R2_p R3 R3_origin relations_3d R3_r R3_c R3_s
Predefined manifolds of sympy.diffgeom.rn