# Source code for sympy.polys.specialpolys

"""Functions for generating interesting polynomials, e.g. for benchmarking. """

from sympy.core import Add, Mul, Symbol, sympify, Dummy, symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.core.singleton import S

from sympy.polys.polytools import Poly, PurePoly
from sympy.polys.polyutils import _analyze_gens

from sympy.polys.polyclasses import DMP

from sympy.polys.densebasic import (
dmp_zero, dmp_one, dmp_ground, dmp_normal,
dup_from_raw_dict, dmp_raise, dup_random
)

from sympy.polys.densearith import (
)

from sympy.polys.factortools import (
dup_zz_cyclotomic_poly
)

from sympy.polys.domains import ZZ

from sympy.ntheory import nextprime

from sympy.utilities import cythonized, subsets

[docs]def swinnerton_dyer_poly(n, x=None, **args): """Generates n-th Swinnerton-Dyer polynomial in x. """ from numberfields import minimal_polynomial if n <= 0: raise ValueError( "can't generate Swinnerton-Dyer polynomial of order %s" % n) if x is not None: sympify(x) else: x = Dummy('x') if n > 3: p = 2 a = [sqrt(2)] for i in xrange(2, n + 1): p = nextprime(p) a.append(sqrt(p)) return minimal_polynomial(Add(*a), x, polys=args.get('polys', False)) if n == 1: ex = x**2 - 2 elif n == 2: ex = x**4 - 10*x**2 + 1 elif n == 3: ex = x**8 - 40*x**6 + 352*x**4 - 960*x**2 + 576 if not args.get('polys', False): return ex else: return PurePoly(ex, x)
[docs]def cyclotomic_poly(n, x=None, **args): """Generates cyclotomic polynomial of order n in x. """ if n <= 0: raise ValueError( "can't generate cyclotomic polynomial of order %s" % n) poly = DMP(dup_zz_cyclotomic_poly(int(n), ZZ), ZZ) if x is not None: poly = Poly.new(poly, x) else: poly = PurePoly.new(poly, Dummy('x')) if not args.get('polys', False): return poly.as_expr() else: return poly
[docs]def symmetric_poly(n, *gens, **args): """Generates symmetric polynomial of order n. """ gens = _analyze_gens(gens) if n < 0 or n > len(gens) or not gens: raise ValueError("can't generate symmetric polynomial of order %s for %s" % (n, gens)) elif not n: poly = S.One else: poly = Add(*[ Mul(*s) for s in subsets(gens, int(n)) ]) if not args.get('polys', False): return poly else: return Poly(poly, *gens)
[docs]def random_poly(x, n, inf, sup, domain=ZZ, polys=False): """Return a polynomial of degree n with coefficients in [inf, sup]. """ poly = Poly(dup_random(n, inf, sup, domain), x, domain=domain) if not polys: return poly.as_expr() else: return poly
@cythonized("n,i,j")
[docs]def interpolating_poly(n, x, X='x', Y='y'): """Construct Lagrange interpolating polynomial for n data points. """ if isinstance(X, str): X = symbols("%s:%s" % (X, n)) if isinstance(Y, str): Y = symbols("%s:%s" % (Y, n)) coeffs = [] for i in xrange(0, n): numer = [] denom = [] for j in xrange(0, n): if i == j: continue numer.append(x - X[j]) denom.append(X[i] - X[j]) numer = Mul(*numer) denom = Mul(*denom) coeffs.append(numer/denom) return Add(*[ coeff*y for coeff, y in zip(coeffs, Y) ])