SymPy is an open-source Python library for symbolic mathematics. It supports combinatorics, calculus, equation solving, statistics, physics, geometry, discrete mathematics, cryptography, and parsing, making symbolic calculations practical without implementing every operation from scratch. section 2.1.1
Use SymPy to:
- Calculate combinatorial quantities such as binomial coefficients and Stirling numbers. section 2.1.1
- Formulate constrained optimization problems with symbolic expressions, derivatives, and Lagrange multipliers. section 2.1.3
- Solve symbolic equations produced from objective functions and constraints. section 2.1.3
Counting and optimizing
A binomial coefficient can be computed with `from sympy import binomial` and `binomial(5, 3)`. For a ticket-sales problem with the constraint x + y = 10,000, SymPy differentiates a Lagrangian and solves for approximately 6,424 in-person and 3,576 online tickets, producing a maximum profit of $2,087,260. section 2.1.1 section 2.1.3
from sympy import binomial print(binomial(5,3))
Inspect the compact Python listing for calculating a binomial coefficient. section 2.1.1
Listing 2.5 Maximizing profits using Lagrange multipliers
import sympy as sym
x,y=sym.var('x, y', positive=True) #1
f=155*x+(0.001*x**sym.Rational(3,2)+70)*y-1000000 #2
g=x+y-10000 #3
lamda=sym.symbols('lambda') #4
Lagr=f-lamda*g #5
eqs = [sym.diff(Lagr, x), sym.diff(Lagr, y), g] #6
sol=sym.solve(eqs,[x,y,lamda], dict=True) #7
def getValueOf(k, L):
for d in L:
if k in d:
return d[k]
profit=[f.subs(p) for p in sol]
print("optimal number of physical ticket sales: x = %.0f" % getValueOf(x, sol))
print("optimal number of online ticket sales: y = %.0f" % getValueOf(y, sol))
print("Expected profil: f(x,y) = $%.4f" % profit[0])
Inspect the complete SymPy implementation that defines the objective and constraint, constructs the Lagrangian, differentiates it, and solves the resulting equations. section 2.1.3


