[docs]defsqrt(arg):"""The square root function sqrt(x) -> Returns the principal square root of x. Examples ======== >>> from sympy import sqrt, Symbol >>> x = Symbol('x') >>> sqrt(x) sqrt(x) >>> sqrt(x)**2 x Note that sqrt(x**2) does not simplify to x. >>> sqrt(x**2) sqrt(x**2) This is because the two are not equal to each other in general. For example, consider x == -1: >>> from sympy import Eq >>> Eq(sqrt(x**2), x).subs(x, -1) False This is because sqrt computes the principal square root, so the square may put the argument in a different branch. This identity does hold if x is positive: >>> y = Symbol('y', positive=True) >>> sqrt(y**2) y You can force this simplification by using the powdenest() function with the force option set to True: >>> from sympy import powdenest >>> sqrt(x**2) sqrt(x**2) >>> powdenest(sqrt(x**2), force=True) x To get both branches of the square root you can use the rootof function: >>> from sympy import rootof >>> [rootof(x**2-3,i) for i in (0,1)] [-sqrt(3), sqrt(3)] See Also ======== sympy.polys.rootoftools.rootof, root, real_root References ========== .. [1] http://en.wikipedia.org/wiki/Square_root .. [2] http://en.wikipedia.org/wiki/Principal_value """# arg = sympify(arg) is handled by PowreturnPow(arg,S.Half)

defcbrt(arg):"""This function computes the principial cube root of `arg`, so it's just a shortcut for `arg**Rational(1, 3)`. Examples ======== >>> from sympy import cbrt, Symbol >>> x = Symbol('x') >>> cbrt(x) x**(1/3) >>> cbrt(x)**3 x Note that cbrt(x**3) does not simplify to x. >>> cbrt(x**3) (x**3)**(1/3) This is because the two are not equal to each other in general. For example, consider `x == -1`: >>> from sympy import Eq >>> Eq(cbrt(x**3), x).subs(x, -1) False This is because cbrt computes the principal cube root, this identity does hold if `x` is positive: >>> y = Symbol('y', positive=True) >>> cbrt(y**3) y See Also ======== sympy.polys.rootoftools.rootof, root, real_root References ========== * http://en.wikipedia.org/wiki/Cube_root * http://en.wikipedia.org/wiki/Principal_value """returnPow(arg,Rational(1,3))

[docs]defroot(arg,n,k=0):"""root(x, n, k) -> Returns the k-th n-th root of x, defaulting to the principle root (k=0). Examples ======== >>> from sympy import root, Rational >>> from sympy.abc import x, n >>> root(x, 2) sqrt(x) >>> root(x, 3) x**(1/3) >>> root(x, n) x**(1/n) >>> root(x, -Rational(2, 3)) x**(-3/2) To get the k-th n-th root, specify k: >>> root(-2, 3, 2) -(-1)**(2/3)*2**(1/3) To get all n n-th roots you can use the rootof function. The following examples show the roots of unity for n equal 2, 3 and 4: >>> from sympy import rootof, I >>> [rootof(x**2 - 1, i) for i in range(2)] [-1, 1] >>> [rootof(x**3 - 1,i) for i in range(3)] [1, -1/2 - sqrt(3)*I/2, -1/2 + sqrt(3)*I/2] >>> [rootof(x**4 - 1,i) for i in range(4)] [-1, 1, -I, I] SymPy, like other symbolic algebra systems, returns the complex root of negative numbers. This is the principal root and differs from the text-book result that one might be expecting. For example, the cube root of -8 does not come back as -2: >>> root(-8, 3) 2*(-1)**(1/3) The real_root function can be used to either make the principle result real (or simply to return the real root directly): >>> from sympy import real_root >>> real_root(_) -2 >>> real_root(-32, 5) -2 Alternatively, the n//2-th n-th root of a negative number can be computed with root: >>> root(-32, 5, 5//2) -2 See Also ======== sympy.polys.rootoftools.rootof sympy.core.power.integer_nthroot sqrt, real_root References ========== * http://en.wikipedia.org/wiki/Square_root * http://en.wikipedia.org/wiki/Real_root * http://en.wikipedia.org/wiki/Root_of_unity * http://en.wikipedia.org/wiki/Principal_value * http://mathworld.wolfram.com/CubeRoot.html """n=sympify(n)ifk:returnPow(arg,S.One/n)*S.NegativeOne**(2*k/n)returnPow(arg,1/n)

defreal_root(arg,n=None):"""Return the real nth-root of arg if possible. If n is omitted then all instances of (-n)**(1/odd) will be changed to -n**(1/odd); this will only create a real root of a principle root -- the presence of other factors may cause the result to not be real. Examples ======== >>> from sympy import root, real_root, Rational >>> from sympy.abc import x, n >>> real_root(-8, 3) -2 >>> root(-8, 3) 2*(-1)**(1/3) >>> real_root(_) -2 If one creates a non-principle root and applies real_root, the result will not be real (so use with caution): >>> root(-8, 3, 2) -2*(-1)**(2/3) >>> real_root(_) -2*(-1)**(2/3) See Also ======== sympy.polys.rootoftools.rootof sympy.core.power.integer_nthroot root, sqrt """fromsympyimportim,PiecewiseifnisnotNone:try:n=as_int(n)arg=sympify(arg)ifarg.is_positiveorarg.is_negative:rv=root(arg,n)else:raiseValueErrorexceptValueError:returnroot(arg,n)*Piecewise((S.One,~Equality(im(arg),0)),(Pow(S.NegativeOne,S.One/n)**(2*floor(n/2)),And(Equality(n%2,1),arg<0)),(S.One,True))else:rv=sympify(arg)n1pow=Transform(lambdax:-(-x.base)**x.exp,lambdax:x.is_Powandx.base.is_negativeandx.exp.is_Rationalandx.exp.p==1andx.exp.q%2)returnrv.xreplace(n1pow)############################################################################################################ MINIMUM and MAXIMUM ############################################################################################################classMinMaxBase(Expr,LatticeOp):def__new__(cls,*args,**assumptions):ifnotargs:raiseValueError("The Max/Min functions must have arguments.")args=(sympify(arg)forarginargs)# first standard filter, for cls.zero and cls.identity# also reshape Max(a, Max(b, c)) to Max(a, b, c)try:_args=frozenset(cls._new_args_filter(args))exceptShortCircuit:returncls.zero# second filter# variant I: remove ones which can be removed# args = cls._collapse_arguments(set(_args), **assumptions)# variant II: find local zerosargs=cls._find_localzeros(set(_args),**assumptions)ifnotargs:returncls.identityeliflen(args)==1:returnargs.pop()else:# base creation# XXX should _args be made canonical with sorting?_args=frozenset(args)obj=Expr.__new__(cls,_args,**assumptions)obj._argset=_argsreturnobj@classmethoddef_new_args_filter(cls,arg_sequence):""" Generator filtering args. first standard filter, for cls.zero and cls.identity. Also reshape Max(a, Max(b, c)) to Max(a, b, c), and check arguments for comparability """forarginarg_sequence:# pre-filter, checking comparability of argumentsif(notisinstance(arg,Expr))or(arg.is_realisFalse)or(argisS.ComplexInfinity):raiseValueError("The argument '%s' is not comparable."%arg)ifarg==cls.zero:raiseShortCircuit(arg)elifarg==cls.identity:continueelifarg.func==cls:forxinarg.args:yieldxelse:yieldarg@classmethoddef_find_localzeros(cls,values,**options):""" Sequentially allocate values to localzeros. When a value is identified as being more extreme than another member it replaces that member; if this is never true, then the value is simply appended to the localzeros. """localzeros=set()forvinvalues:is_newzero=Truelocalzeros_=list(localzeros)forzinlocalzeros_:ifid(v)==id(z):is_newzero=Falseelse:con=cls._is_connected(v,z)ifcon:is_newzero=FalseifconisTrueorcon==cls:localzeros.remove(z)localzeros.update([v])ifis_newzero:localzeros.update([v])returnlocalzeros@classmethoddef_is_connected(cls,x,y):""" Check if x and y are connected somehow. """fromsympy.core.exprtoolsimportfactor_termsdefhit(v,t,f):ifnotv.is_Relational:returntifvelsefforiinrange(2):ifx==y:returnTruer=hit(x>=y,Max,Min)ifrisnotNone:returnrr=hit(y<=x,Max,Min)ifrisnotNone:returnrr=hit(x<=y,Min,Max)ifrisnotNone:returnrr=hit(y>=x,Min,Max)ifrisnotNone:returnr# simplification can be expensive, so be conservative# in what is attemptedx=factor_terms(x-y)y=S.ZeroreturnFalsedef_eval_derivative(self,s):# f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s)i=0l=[]forainself.args:i+=1da=a.diff(s)ifdaisS.Zero:continuetry:df=self.fdiff(i)exceptArgumentIndexError:df=Function.fdiff(self,i)l.append(df*da)returnAdd(*l)defevalf(self,prec=None,**options):returnself.func(*[a.evalf(prec,options)forainself.args])n=evalf_eval_is_algebraic=lambdas:_torf(i.is_algebraicforiins.args)_eval_is_antihermitian=lambdas:_torf(i.is_antihermitianforiins.args)_eval_is_commutative=lambdas:_torf(i.is_commutativeforiins.args)_eval_is_complex=lambdas:_torf(i.is_complexforiins.args)_eval_is_composite=lambdas:_torf(i.is_compositeforiins.args)_eval_is_even=lambdas:_torf(i.is_evenforiins.args)_eval_is_finite=lambdas:_torf(i.is_finiteforiins.args)_eval_is_hermitian=lambdas:_torf(i.is_hermitianforiins.args)_eval_is_imaginary=lambdas:_torf(i.is_imaginaryforiins.args)_eval_is_infinite=lambdas:_torf(i.is_infiniteforiins.args)_eval_is_integer=lambdas:_torf(i.is_integerforiins.args)_eval_is_irrational=lambdas:_torf(i.is_irrationalforiins.args)_eval_is_negative=lambdas:_torf(i.is_negativeforiins.args)_eval_is_noninteger=lambdas:_torf(i.is_nonintegerforiins.args)_eval_is_nonnegative=lambdas:_torf(i.is_nonnegativeforiins.args)_eval_is_nonpositive=lambdas:_torf(i.is_nonpositiveforiins.args)_eval_is_nonzero=lambdas:_torf(i.is_nonzeroforiins.args)_eval_is_odd=lambdas:_torf(i.is_oddforiins.args)_eval_is_polar=lambdas:_torf(i.is_polarforiins.args)_eval_is_positive=lambdas:_torf(i.is_positiveforiins.args)_eval_is_prime=lambdas:_torf(i.is_primeforiins.args)_eval_is_rational=lambdas:_torf(i.is_rationalforiins.args)_eval_is_real=lambdas:_torf(i.is_realforiins.args)_eval_is_transcendental=lambdas:_torf(i.is_transcendentalforiins.args)_eval_is_zero=lambdas:_torf(i.is_zeroforiins.args)

[docs]classMax(MinMaxBase,Application):""" Return, if possible, the maximum value of the list. When number of arguments is equal one, then return this argument. When number of arguments is equal two, then return, if possible, the value from (a, b) that is >= the other. In common case, when the length of list greater than 2, the task is more complicated. Return only the arguments, which are greater than others, if it is possible to determine directional relation. If is not possible to determine such a relation, return a partially evaluated result. Assumptions are used to make the decision too. Also, only comparable arguments are permitted. It is named ``Max`` and not ``max`` to avoid conflicts with the built-in function ``max``. Examples ======== >>> from sympy import Max, Symbol, oo >>> from sympy.abc import x, y >>> p = Symbol('p', positive=True) >>> n = Symbol('n', negative=True) >>> Max(x, -2) #doctest: +SKIP Max(x, -2) >>> Max(x, -2).subs(x, 3) 3 >>> Max(p, -2) p >>> Max(x, y) #doctest: +SKIP Max(x, y) >>> Max(x, y) == Max(y, x) True >>> Max(x, Max(y, z)) #doctest: +SKIP Max(x, y, z) >>> Max(n, 8, p, 7, -oo) #doctest: +SKIP Max(8, p) >>> Max (1, x, oo) oo * Algorithm The task can be considered as searching of supremums in the directed complete partial orders [1]_. The source values are sequentially allocated by the isolated subsets in which supremums are searched and result as Max arguments. If the resulted supremum is single, then it is returned. The isolated subsets are the sets of values which are only the comparable with each other in the current set. E.g. natural numbers are comparable with each other, but not comparable with the `x` symbol. Another example: the symbol `x` with negative assumption is comparable with a natural number. Also there are "least" elements, which are comparable with all others, and have a zero property (maximum or minimum for all elements). E.g. `oo`. In case of it the allocation operation is terminated and only this value is returned. Assumption: - if A > B > C then A > C - if A == B then B can be removed References ========== .. [1] http://en.wikipedia.org/wiki/Directed_complete_partial_order .. [2] http://en.wikipedia.org/wiki/Lattice_%28order%29 See Also ======== Min : find minimum values """zero=S.Infinityidentity=S.NegativeInfinitydeffdiff(self,argindex):fromsympyimportHeavisiden=len(self.args)if0<argindexandargindex<=n:argindex-=1ifn==2:returnHeaviside(self.args[argindex]-self.args[1-argindex])newargs=tuple([self.args[i]foriinrange(n)ifi!=argindex])returnHeaviside(self.args[argindex]-Max(*newargs))else:raiseArgumentIndexError(self,argindex)def_eval_rewrite_as_Heaviside(self,*args):fromsympyimportHeavisidereturnAdd(*[j*Mul(*[Heaviside(j-i)foriinargsifi!=j]) \
forjinargs])def_eval_is_positive(self):returnfuzzy_or(a.is_positiveforainself.args)def_eval_is_nonnegative(self):returnfuzzy_or(a.is_nonnegativeforainself.args)def_eval_is_negative(self):returnfuzzy_and(a.is_negativeforainself.args)