bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def points(self): """ Return a list of the generating points in this Mordell-Weil group.
def points(self): """ Return a list of the generating points in this Mordell-Weil group.
472,300
def _latex_(self): """ Return Latex representation of this Maxima object.
def _latex_(self): """ Return Latex representation of this Maxima object.
472,301
def _call_(self, x): """ Construct a module with basis from the data in ``x``
def _call_(self, x): """ Construct a module with basis from the data in ``x``
472,302
def is_abelian(self): """ Returns whether this category is abelian
def is_abelian(self): """ Returns whether this category is abelian
472,303
def module_morphism(self, on_basis = None, diagonal = None, triangular = None, **keywords): r""" Constructs morphisms by linearity
def module_morphism(self, on_basis = None, diagonal = None, triangular = None, **keywords): r""" Constructs morphisms by linearity
472,304
def module_morphism(self, on_basis = None, diagonal = None, triangular = None, **keywords): r""" Constructs morphisms by linearity
def module_morphism(self, on_basis = None, diagonal = None, triangular = None, **keywords): r""" Constructs morphisms by linearity
472,305
def ModularForms(group = 1, weight = 2, base_ring = None, use_cache = True, prec = defaults.DEFAULT_PRECISION): r""" Create an ambient space of modular forms. INPUT: - ``group`` - A congruence subgroup or a Dirichlet character eps. - ``weight`` - int, the weight, which must be an integer = 1. - ``base_ring`` - the base ring (ignored if group is a Dirichlet character) Create using the command ModularForms(group, weight, base_ring) where group could be either a congruence subgroup or a Dirichlet character. EXAMPLES: First we create some spaces with trivial character:: sage: ModularForms(Gamma0(11),2).dimension() 2 sage: ModularForms(Gamma0(1),12).dimension() 2 If we give an integer N for the congruence subgroup, it defaults to `\Gamma_0(N)`:: sage: ModularForms(1,12).dimension() 2 sage: ModularForms(11,4) Modular Forms space of dimension 4 for Congruence Subgroup Gamma0(11) of weight 4 over Rational Field We create some spaces for `\Gamma_1(N)`. :: sage: ModularForms(Gamma1(13),2) Modular Forms space of dimension 13 for Congruence Subgroup Gamma1(13) of weight 2 over Rational Field sage: ModularForms(Gamma1(13),2).dimension() 13 sage: [ModularForms(Gamma1(7),k).dimension() for k in [2,3,4,5]] [5, 7, 9, 11] sage: ModularForms(Gamma1(5),11).dimension() 12 We create a space with character:: sage: e = (DirichletGroup(13).0)^2 sage: e.order() 6 sage: M = ModularForms(e, 2); M Modular Forms space of dimension 3, character [zeta6] and weight 2 over Cyclotomic Field of order 6 and degree 2 sage: f = M.T(2).charpoly('x'); f x^3 + (-2*zeta6 - 2)*x^2 - 2*zeta6*x + 14*zeta6 - 7 sage: f.factor() (x - 2*zeta6 - 1) * (x - zeta6 - 2) * (x + zeta6 + 1) We can also create spaces corresponding to the groups `\GammaH(N)` intermediate between `\Gamma_0(N)` and `\Gamma_1(N)`:: sage: G = GammaH(30, [11]) sage: M = ModularForms(G, 2); M Modular Forms space of dimension 20 for Congruence Subgroup Gamma_H(30) with H generated by [11] of weight 2 over Rational Field sage: M.T(7).charpoly().factor() (x + 4) * x^2 * (x - 6)^4 * (x + 6)^4 * (x - 8)^7 * (x^2 + 4) More examples of spaces with character:: sage: e = DirichletGroup(5, RationalField()).gen(); e Dirichlet character modulo 5 of conductor 5 mapping 2 |--> -1 sage: m = ModularForms(e, 2); m Modular Forms space of dimension 2, character [-1] and weight 2 over Rational Field sage: m == loads(dumps(m)) True sage: m.T(2).charpoly('x') x^2 - 1 sage: m = ModularForms(e, 6); m.dimension() 4 sage: m.T(2).charpoly('x') x^4 - 917*x^2 - 42284 This came up in a subtle bug (trac #5923):: sage: ModularForms(gp(1), gap(12)) Modular Forms space of dimension 2 for Modular Group SL(2,Z) of weight 12 over Rational Field This came up in another bug (related to trac #8630):: sage: chi = DirichletGroup(109, CyclotomicField(3)).0 sage: ModularForms(chi, 2, base_ring = CyclotomicField(15)) Modular Forms space of dimension 10, character [zeta3 + 1] and weight 2 over Cyclotomic Field of order 15 and degree 8 We create some weight 1 spaces. The first example works fine, since we can prove purely by Riemann surface theory that there are no weight 1 cusp forms:: sage: M = ModularForms(Gamma1(11), 1); M Modular Forms space of dimension 5 for Congruence Subgroup Gamma1(11) of weight 1 over Rational Field sage: M.basis() [ 1 + 22*q^5 + O(q^6), q + 4*q^5 + O(q^6), q^2 - 4*q^5 + O(q^6), q^3 - 5*q^5 + O(q^6), q^4 - 3*q^5 + O(q^6) ] sage: M.cuspidal_subspace().basis() [ ] sage: M == M.eisenstein_subspace() True This example doesn't work so well, because we can't calculate the cusp forms; but we can still work with the Eisenstein series. sage: M = ModularForms(Gamma1(57), 1); M Modular Forms space of dimension (unknown) for Congruence Subgroup Gamma1(57) of weight 1 over Rational Field sage: M.basis() Traceback (most recent call last): ... NotImplementedError: Computation of dimensions of weight 1 cusp forms spaces not implemented in general sage: M.cuspidal_subspace().basis() Traceback (most recent call last): ... NotImplementedError: Computation of dimensions of weight 1 cusp forms spaces not implemented in general sage: E = M.eisenstein_subspace(); E Eisenstein subspace of dimension 36 of Modular Forms space of dimension (unknown) for Congruence Subgroup Gamma1(57) of weight 1 over Rational Field sage: (E.0 + E.2).q_expansion(40) 1 + q^2 + 1473/2*q^36 - 1101/2*q^37 + q^38 - 373/2*q^39 + O(q^40) """ if isinstance(group, dirichlet.DirichletCharacter): if base_ring is None: base_ring = group.minimize_base_ring().base_ring() if base_ring is None: base_ring = rings.QQ if isinstance(group, dirichlet.DirichletCharacter) \ or arithgroup.is_CongruenceSubgroup(group): level = group.level() else: level = group key = canonical_parameters(group, level, weight, base_ring) if use_cache and _cache.has_key(key): M = _cache[key]() if not (M is None): M.set_precision(prec) return M (level, group, weight, base_ring) = key M = None if arithgroup.is_Gamma0(group): M = ambient_g0.ModularFormsAmbient_g0_Q(group.level(), weight) if base_ring != rings.QQ: M = ambient_R.ModularFormsAmbient_R(M, base_ring) elif arithgroup.is_Gamma1(group): M = ambient_g1.ModularFormsAmbient_g1_Q(group.level(), weight) if base_ring != rings.QQ: M = ambient_R.ModularFormsAmbient_R(M, base_ring) elif arithgroup.is_GammaH(group): M = ambient_g1.ModularFormsAmbient_gH_Q(group, weight) if base_ring != rings.QQ: M = ambient_R.ModularFormsAmbient_R(M, base_ring) elif isinstance(group, dirichlet.DirichletCharacter): eps = group if eps.base_ring().characteristic() != 0: # TODO -- implement this # Need to add a lift_to_char_0 function for characters, # and need to still remember eps. raise NotImplementedError, "currently the character must be over a ring of characteristic 0." eps = eps.minimize_base_ring() if eps.is_trivial(): return ModularForms(eps.modulus(), weight, base_ring, use_cache = use_cache, prec = prec) M = ambient_eps.ModularFormsAmbient_eps(eps, weight) if base_ring != eps.base_ring(): M = M.base_extend(base_ring) # ambient_R.ModularFormsAmbient_R(M, base_ring) if M is None: raise NotImplementedError, \ "computation of requested space of modular forms not defined or implemented" M.set_precision(prec) _cache[key] = weakref.ref(M) return M
def ModularForms(group = 1, weight = 2, base_ring = None, use_cache = True, prec = defaults.DEFAULT_PRECISION): r""" Create an ambient space of modular forms. INPUT: - ``group`` - A congruence subgroup or a Dirichlet character eps. - ``weight`` - int, the weight, which must be an integer = 1. - ``base_ring`` - the base ring (ignored if group is a Dirichlet character) Create using the command ModularForms(group, weight, base_ring) where group could be either a congruence subgroup or a Dirichlet character. EXAMPLES: First we create some spaces with trivial character:: sage: ModularForms(Gamma0(11),2).dimension() 2 sage: ModularForms(Gamma0(1),12).dimension() 2 If we give an integer N for the congruence subgroup, it defaults to `\Gamma_0(N)`:: sage: ModularForms(1,12).dimension() 2 sage: ModularForms(11,4) Modular Forms space of dimension 4 for Congruence Subgroup Gamma0(11) of weight 4 over Rational Field We create some spaces for `\Gamma_1(N)`. :: sage: ModularForms(Gamma1(13),2) Modular Forms space of dimension 13 for Congruence Subgroup Gamma1(13) of weight 2 over Rational Field sage: ModularForms(Gamma1(13),2).dimension() 13 sage: [ModularForms(Gamma1(7),k).dimension() for k in [2,3,4,5]] [5, 7, 9, 11] sage: ModularForms(Gamma1(5),11).dimension() 12 We create a space with character:: sage: e = (DirichletGroup(13).0)^2 sage: e.order() 6 sage: M = ModularForms(e, 2); M Modular Forms space of dimension 3, character [zeta6] and weight 2 over Cyclotomic Field of order 6 and degree 2 sage: f = M.T(2).charpoly('x'); f x^3 + (-2*zeta6 - 2)*x^2 - 2*zeta6*x + 14*zeta6 - 7 sage: f.factor() (x - 2*zeta6 - 1) * (x - zeta6 - 2) * (x + zeta6 + 1) We can also create spaces corresponding to the groups `\Gamma_H(N)` intermediate between `\Gamma_0(N)` and `\Gamma_1(N)`:: sage: G = GammaH(30, [11]) sage: M = ModularForms(G, 2); M Modular Forms space of dimension 20 for Congruence Subgroup Gamma_H(30) with H generated by [11] of weight 2 over Rational Field sage: M.T(7).charpoly().factor() (x + 4) * x^2 * (x - 6)^4 * (x + 6)^4 * (x - 8)^7 * (x^2 + 4) More examples of spaces with character:: sage: e = DirichletGroup(5, RationalField()).gen(); e Dirichlet character modulo 5 of conductor 5 mapping 2 |--> -1 sage: m = ModularForms(e, 2); m Modular Forms space of dimension 2, character [-1] and weight 2 over Rational Field sage: m == loads(dumps(m)) True sage: m.T(2).charpoly('x') x^2 - 1 sage: m = ModularForms(e, 6); m.dimension() 4 sage: m.T(2).charpoly('x') x^4 - 917*x^2 - 42284 This came up in a subtle bug (trac #5923):: sage: ModularForms(gp(1), gap(12)) Modular Forms space of dimension 2 for Modular Group SL(2,Z) of weight 12 over Rational Field This came up in another bug (related to trac #8630):: sage: chi = DirichletGroup(109, CyclotomicField(3)).0 sage: ModularForms(chi, 2, base_ring = CyclotomicField(15)) Modular Forms space of dimension 10, character [zeta3 + 1] and weight 2 over Cyclotomic Field of order 15 and degree 8 We create some weight 1 spaces. The first example works fine, since we can prove purely by Riemann surface theory that there are no weight 1 cusp forms:: sage: M = ModularForms(Gamma1(11), 1); M Modular Forms space of dimension 5 for Congruence Subgroup Gamma1(11) of weight 1 over Rational Field sage: M.basis() [ 1 + 22*q^5 + O(q^6), q + 4*q^5 + O(q^6), q^2 - 4*q^5 + O(q^6), q^3 - 5*q^5 + O(q^6), q^4 - 3*q^5 + O(q^6) ] sage: M.cuspidal_subspace().basis() [ ] sage: M == M.eisenstein_subspace() True This example doesn't work so well, because we can't calculate the cusp forms; but we can still work with the Eisenstein series. sage: M = ModularForms(Gamma1(57), 1); M Modular Forms space of dimension (unknown) for Congruence Subgroup Gamma1(57) of weight 1 over Rational Field sage: M.basis() Traceback (most recent call last): ... NotImplementedError: Computation of dimensions of weight 1 cusp forms spaces not implemented in general sage: M.cuspidal_subspace().basis() Traceback (most recent call last): ... NotImplementedError: Computation of dimensions of weight 1 cusp forms spaces not implemented in general sage: E = M.eisenstein_subspace(); E Eisenstein subspace of dimension 36 of Modular Forms space of dimension (unknown) for Congruence Subgroup Gamma1(57) of weight 1 over Rational Field sage: (E.0 + E.2).q_expansion(40) 1 + q^2 + 1473/2*q^36 - 1101/2*q^37 + q^38 - 373/2*q^39 + O(q^40) """ if isinstance(group, dirichlet.DirichletCharacter): if base_ring is None: base_ring = group.minimize_base_ring().base_ring() if base_ring is None: base_ring = rings.QQ if isinstance(group, dirichlet.DirichletCharacter) \ or arithgroup.is_CongruenceSubgroup(group): level = group.level() else: level = group key = canonical_parameters(group, level, weight, base_ring) if use_cache and _cache.has_key(key): M = _cache[key]() if not (M is None): M.set_precision(prec) return M (level, group, weight, base_ring) = key M = None if arithgroup.is_Gamma0(group): M = ambient_g0.ModularFormsAmbient_g0_Q(group.level(), weight) if base_ring != rings.QQ: M = ambient_R.ModularFormsAmbient_R(M, base_ring) elif arithgroup.is_Gamma1(group): M = ambient_g1.ModularFormsAmbient_g1_Q(group.level(), weight) if base_ring != rings.QQ: M = ambient_R.ModularFormsAmbient_R(M, base_ring) elif arithgroup.is_GammaH(group): M = ambient_g1.ModularFormsAmbient_gH_Q(group, weight) if base_ring != rings.QQ: M = ambient_R.ModularFormsAmbient_R(M, base_ring) elif isinstance(group, dirichlet.DirichletCharacter): eps = group if eps.base_ring().characteristic() != 0: # TODO -- implement this # Need to add a lift_to_char_0 function for characters, # and need to still remember eps. raise NotImplementedError, "currently the character must be over a ring of characteristic 0." eps = eps.minimize_base_ring() if eps.is_trivial(): return ModularForms(eps.modulus(), weight, base_ring, use_cache = use_cache, prec = prec) M = ambient_eps.ModularFormsAmbient_eps(eps, weight) if base_ring != eps.base_ring(): M = M.base_extend(base_ring) # ambient_R.ModularFormsAmbient_R(M, base_ring) if M is None: raise NotImplementedError, \ "computation of requested space of modular forms not defined or implemented" M.set_precision(prec) _cache[key] = weakref.ref(M) return M
472,306
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
def rational_points_iterator(self): r""" Return the rational points on this curve computed via enumeration.
472,307
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
472,308
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
472,309
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
472,310
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
472,311
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
472,312
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
472,313
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
472,314
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
472,315
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
472,316
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
472,317
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
472,318
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
472,319
def cardinality(self): """ Returns the cardinality of this disjoint union.
def cardinality(self): """ Returns the cardinality of this disjoint union.
472,320
def _allowed_options(self): """ Return the allowed options for the Point class.
def _allowed_options(self): """ Return the allowed options for the Point class.
472,321
def _allowed_options(self): """ Return the allowed options for the Point class.
def _allowed_options(self): """ Return the allowed options for the Point class.
472,322
def upgrade(): """ Download and build the latest version of Sage. You must have an internet connection. Also, you will have to restart Sage for the changes to take affect. This upgrades to the latest version of core packages (optional packages are not automatically upgraded). This will not work on systems that don't have a C compiler. .. seealso:: :func:`install_package`, :func:`optional_packages` """ global __installed_packages if os.uname()[0][:6] == 'CYGWIN': print "Upgrade may not work correctly under Microsoft Windows" print "since you can't change an opened file. Quit all" print "instances of Sage and use 'sage -upgrade' instead." return [] os.system('sage -upgrade') __installed_packages = None print "You should quit and restart Sage now."
def upgrade(): """ Download and build the latest version of Sage. You must have an internet connection. Also, you will have to restart Sage for the changes to take affect. This upgrades to the latest version of core packages (optional packages are not automatically upgraded). This will not work on systems that don't have a C compiler. .. seealso:: :func:`install_package`, :func:`optional_packages` """ global __installed_packages if os.uname()[0][:6] == 'CYGWIN': print "Upgrade may not work correctly under Microsoft Windows" print "since you can't change an opened file. Quit all" print "instances of Sage and use 'sage -upgrade' instead." return os.system('sage -upgrade') __installed_packages = None print "You should quit and restart Sage now."
472,323
def desolve(de, dvar, ics=None, ivar=None, show_method=False, contrib_ode=False): r""" Solves a 1st or 2nd order linear ODE via maxima. Including IVP and BVP. *Use* ``desolve? <tab>`` *if the output in truncated in notebook.* INPUT: - ``de`` - an expression or equation representing the ODE - ``dvar`` - the dependent variable (hereafter called ``y``) - ``ics`` - (optional) the initial or boundary conditions - for a first-order equation, specify the initial ``x`` and ``y`` - for a second-order equation, specify the initial ``x``, ``y``, and ``dy/dx``, i.e. write `[x_0, y(x_0), y'(x_0)]` - for a second-order boundary solution, specify initial and final ``x`` and ``y`` boundary conditions, i.e. write `[x_0, y(x_0), x_1, y(x_1)]`. - gives an error if the solution is not SymbolicEquation (as happens for example for Clairaut equation) - ``ivar`` - (optional) the independent variable (hereafter called x), which must be specified if there is more than one independent variable in the equation. - ``show_method`` - (optional) if true, then Sage returns pair ``[solution, method]``, where method is the string describing method which has been used to get solution (Maxima uses the following order for first order equations: linear, separable, exact (including exact with integrating factor), homogeneous, bernoulli, generalized homogeneous) - use carefully in class, see below for the example of the equation which is separable but this property is not recognized by Maxima and equation is solved as exact. - ``contrib_ode`` - (optional) if true, desolve allows to solve clairaut, lagrange, riccati and some other equations. May take a long time and thus turned off by default. Initial conditions can be used only if the result is one SymbolicEquation (does not contain singular solution, for example) OUTPUT: In most cases returns SymbolicEquation which defines the solution implicitly. If the result is in the form y(x)=... (happens for linear eqs.), returns the right-hand side only. The possible constant solutions of separable ODE's are omitted. EXAMPLES:: sage: x = var('x') sage: y = function('y', x) sage: desolve(diff(y,x) + y - 1, y) (c + e^x)*e^(-x) :: sage: f = desolve(diff(y,x) + y - 1, y, ics=[10,2]); f (e^10 + e^x)*e^(-x) :: sage: plot(f) We can also solve second-order differential equations.:: sage: x = var('x') sage: y = function('y', x) sage: de = diff(y,x,2) - y == x sage: desolve(de, y) k1*e^x + k2*e^(-x) - x :: sage: f = desolve(de, y, [10,2,1]); f -x + 5*e^(-x + 10) + 7*e^(x - 10) :: sage: f(x=10) 2 :: sage: diff(f,x)(x=10) 1 :: sage: de = diff(y,x,2) + y == 0 sage: desolve(de, y) k1*sin(x) + k2*cos(x) :: sage: desolve(de, y, [0,1,pi/2,4]) 4*sin(x) + cos(x) :: sage: desolve(y*diff(y,x)+sin(x)==0,y) -1/2*y(x)^2 == c - cos(x) Clairot equation: general and singular solutions:: sage: desolve(diff(y,x)^2+x*diff(y,x)-y==0,y,contrib_ode=True,show_method=True) [[y(x) == c^2 + c*x, y(x) == -1/4*x^2], 'clairault'] For equations involving more variables we specify independent variable:: sage: a,b,c,n=var('a b c n') sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True) [[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]] :: sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True,show_method=True) [[[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]], 'riccati'] Higher orded, not involving independent variable:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y).expand() 1/6*y(x)^3 + k1*y(x) == k2 + x :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3]).expand() 1/6*y(x)^3 - 5/3*y(x) == x - 3/2 :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3],show_method=True) [1/6*y(x)^3 - 5/3*y(x) == x - 3/2, 'freeofx'] Separable equations - Sage returns solution in implicit form:: sage: desolve(diff(y,x)*sin(y) == cos(x),y) -cos(y(x)) == c + sin(x) :: sage: desolve(diff(y,x)*sin(y) == cos(x),y,show_method=True) [-cos(y(x)) == c + sin(x), 'separable'] :: sage: desolve(diff(y,x)*sin(y) == cos(x),y,[pi/2,1]) -cos(y(x)) == sin(x) - cos(1) - 1 Linear equation - Sage returns the expression on the right hand side only:: sage: desolve(diff(y,x)+(y) == cos(x),y) 1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x) :: sage: desolve(diff(y,x)+(y) == cos(x),y,show_method=True) [1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x), 'linear'] :: sage: desolve(diff(y,x)+(y) == cos(x),y,[0,1]) 1/2*(e^x*sin(x) + e^x*cos(x) + 1)*e^(-x) This ODE with separated variables is solved as exact. Explanation - factor does not split `e^{x-y}` in Maxima into `e^{x}e^{y}`:: sage: desolve(diff(y,x)==exp(x-y),y,show_method=True) [-e^x + e^y(x) == c, 'exact'] You can solve Bessel equations. You can also use initial conditions, but you cannot put (sometimes desired) initial condition at x=0, since this point is singlar point of the equation. Anyway, if the solution should be bounded at x=0, then k2=0.:: sage: desolve(x^2*diff(y,x,x)+x*diff(y,x)+(x^2-4)*y==0,y) k1*bessel_j(2, x) + k2*bessel_y(2, x) Difficult ODE produces error:: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Difficult ODE produces error - moreover, takes a long time :: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y,contrib_ode=True) # not tested Some more types od ODE's:: sage: desolve(x*diff(y,x)^2-(1+x*y)*diff(y,x)+y==0,y,contrib_ode=True,show_method=True) [[y(x) == c + log(x), y(x) == c*e^x], 'factor'] :: sage: desolve(diff(y,x)==(x+y)^2,y,contrib_ode=True,show_method=True) [[[x == c - arctan(sqrt(t)), y(x) == -x - sqrt(t)], [x == c + arctan(sqrt(t)), y(x) == -x + sqrt(t)]], 'lagrange'] These two examples produce error (as expected, Maxima 5.18 cannot solve equations from initial conditions). Current Maxima 5.18 returns false answer in this case!:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2]).expand() # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2],show_method=True) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Second order linear ODE:: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y) (k2*x + k1)*e^(-x) + 1/2*sin(x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,show_method=True) [(k2*x + k1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1]) 1/2*(7*x + 6)*e^(-x) + 1/2*sin(x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1],show_method=True) [1/2*(7*x + 6)*e^(-x) + 1/2*sin(x), 'variationofparameters'] :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2]) 3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2],show_method=True) [3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y) (k2*x + k1)*e^(-x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,show_method=True) [(k2*x + k1)*e^(-x), 'constcoeff'] :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1]) (4*x + 3)*e^(-x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1],show_method=True) [(4*x + 3)*e^(-x), 'constcoeff'] :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2]) (2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2],show_method=True) [(2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x), 'constcoeff'] This equation can be solved within Maxima but not within Sage. It needs assumptions assume(x>0,y>0) and works in Maxima, but not in Sage:: sage: assume(x>0) # not tested sage: assume(y>0) # not tested sage: desolve(x*diff(y,x)-x*sqrt(y^2+x^2)-y,y,show_method=True) # not tested TESTS: Trac #6479 fixed:: sage: x = var('x') sage: y = function('y', x) sage: desolve( diff(y,x,x) == 0, y, [0,0,1]) x :: sage: desolve( diff(y,x,x) == 0, y, [0,1,1]) x + 1 Trac #9835 fixed:: sage: x = var('x') sage: y = function('y', x) sage: desolve(diff(y,x,2)+y*(1-y^2)==0,y,[0,-1,1,1]) Traceback (most recent call last): ... NotImplementedError: Unable to use initial condition for this equation (freeofx). AUTHORS: - David Joyner (1-2006) - Robert Bradshaw (10-2008) - Robert Marik (10-2009) """ if is_SymbolicEquation(de): de = de.lhs() - de.rhs() if is_SymbolicVariable(dvar): raise ValueError, "You have to declare dependent variable as a function, eg. y=function('y',x)" # for backwards compatibility if isinstance(dvar, list): dvar, ivar = dvar elif ivar is None: ivars = de.variables() ivars = [t for t in ivars if t is not dvar] if len(ivars) != 1: raise ValueError, "Unable to determine independent variable, please specify." ivar = ivars[0] def sanitize_var(exprs): return exprs.replace("'"+dvar_str+"("+ivar_str+")",dvar_str) de00 = de._maxima_() P = de00.parent() dvar_str=P(dvar.operator()).str() ivar_str=P(ivar).str() de00 = de00.str() de0 = sanitize_var(de00) ode_solver="ode2" cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y(x),x) soln = P(cmd) if str(soln).strip() == 'false': if contrib_ode: ode_solver="contrib_ode" P("load('contrib_ode)") cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # (TEMP:contrib_ode(x*('diff(y,x,1))^2-(x*y+1)*'diff(y,x,1)+y,y,x), if TEMP=false then TEMP else substitute(y=y(x),TEMP)) soln = P(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this ODE." else: raise NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." if show_method: maxima_method=P("method") if (ics is not None): if not is_SymbolicEquation(soln.sage()): if not show_method: maxima_method=P("method") raise NotImplementedError, "Unable to use initial condition for this equation (%s)."%(str(maxima_method).strip()) if len(ics) == 2: tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() cmd="(TEMP:ic1(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=P(cmd) if len(ics) == 3: #fixed ic2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima P("ic2_sage(soln,xa,ya,dya):=block([programmode:true,backsubst:true,singsolve:true,temp,%k2,%k1,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(dya), boundtest('%k1,%k1), boundtest('%k2,%k2), \ temp: lhs(soln) - rhs(soln), \ TEMP_k:solve([subst([xa,ya],soln), subst([dya,xa], lhs(dya)=-subst(0,lhs(dya),diff(temp,lhs(xa)))/diff(temp,lhs(ya)))],[%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)), TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") tempic=P(ivar==ics[0]).str() tempic=tempic+","+P(dvar==ics[1]).str() tempic=tempic+",'diff("+dvar_str+","+ivar_str+")="+P(ics[2]).str() cmd="(TEMP:ic2_sage(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=P(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this IVP. Remove the initial condition to get the general solution." if len(ics) == 4: #fixed bc2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima P("bc2_sage(soln,xa,ya,xb,yb):=block([programmode:true,backsubst:true,singsolve:true,temp,%k1,%k2,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(xb), noteqn(yb), boundtest('%k1,%k1), boundtest('%k2,%k2), \ TEMP_k:solve([subst([xa,ya],soln), subst([xb,yb],soln)], [%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)),TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") cmd="bc2_sage(%s(%s,%s,%s),%s,%s=%s,%s,%s=%s)"%(ode_solver,de00,dvar_str,ivar_str,P(ivar==ics[0]).str(),dvar_str,P(ics[1]).str(),P(ivar==ics[2]).str(),dvar_str,P(ics[3]).str()) cmd="(TEMP:%s,substitute(%s=%s(%s),TEMP))"%(cmd,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:bc2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,x=%pi/2,y=2),substitute(y=y(x),TEMP)) soln=P(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this BVP. Remove the initial condition to get the general solution." soln=soln.sage() if is_SymbolicEquation(soln) and soln.lhs() == dvar: # Remark: Here we do not check that the right hand side does not depend on dvar. # This probably will not hapen for soutions obtained via ode2, anyway. soln = soln.rhs() if show_method: return [soln,maxima_method.str()] else: return soln
def desolve(de, dvar, ics=None, ivar=None, show_method=False, contrib_ode=False): r""" Solves a 1st or 2nd order linear ODE via maxima. Including IVP and BVP. *Use* ``desolve? <tab>`` *if the output in truncated in notebook.* INPUT: - ``de`` - an expression or equation representing the ODE - ``dvar`` - the dependent variable (hereafter called ``y``) - ``ics`` - (optional) the initial or boundary conditions - for a first-order equation, specify the initial ``x`` and ``y`` - for a second-order equation, specify the initial ``x``, ``y``, and ``dy/dx``, i.e. write `[x_0, y(x_0), y'(x_0)]` - for a second-order boundary solution, specify initial and final ``x`` and ``y`` boundary conditions, i.e. write `[x_0, y(x_0), x_1, y(x_1)]`. - gives an error if the solution is not SymbolicEquation (as happens for example for Clairaut equation) - ``ivar`` - (optional) the independent variable (hereafter called x), which must be specified if there is more than one independent variable in the equation. - ``show_method`` - (optional) if true, then Sage returns pair ``[solution, method]``, where method is the string describing method which has been used to get solution (Maxima uses the following order for first order equations: linear, separable, exact (including exact with integrating factor), homogeneous, bernoulli, generalized homogeneous) - use carefully in class, see below for the example of the equation which is separable but this property is not recognized by Maxima and equation is solved as exact. - ``contrib_ode`` - (optional) if true, desolve allows to solve clairaut, lagrange, riccati and some other equations. May take a long time and thus turned off by default. Initial conditions can be used only if the result is one SymbolicEquation (does not contain singular solution, for example) OUTPUT: In most cases returns SymbolicEquation which defines the solution implicitly. If the result is in the form y(x)=... (happens for linear eqs.), returns the right-hand side only. The possible constant solutions of separable ODE's are omitted. EXAMPLES:: sage: x = var('x') sage: y = function('y', x) sage: desolve(diff(y,x) + y - 1, y) (c + e^x)*e^(-x) :: sage: f = desolve(diff(y,x) + y - 1, y, ics=[10,2]); f (e^10 + e^x)*e^(-x) :: sage: plot(f) We can also solve second-order differential equations.:: sage: x = var('x') sage: y = function('y', x) sage: de = diff(y,x,2) - y == x sage: desolve(de, y) k1*e^x + k2*e^(-x) - x :: sage: f = desolve(de, y, [10,2,1]); f -x + 5*e^(-x + 10) + 7*e^(x - 10) :: sage: f(x=10) 2 :: sage: diff(f,x)(x=10) 1 :: sage: de = diff(y,x,2) + y == 0 sage: desolve(de, y) k1*sin(x) + k2*cos(x) :: sage: desolve(de, y, [0,1,pi/2,4]) 4*sin(x) + cos(x) :: sage: desolve(y*diff(y,x)+sin(x)==0,y) -1/2*y(x)^2 == c - cos(x) Clairot equation: general and singular solutions:: sage: desolve(diff(y,x)^2+x*diff(y,x)-y==0,y,contrib_ode=True,show_method=True) [[y(x) == c^2 + c*x, y(x) == -1/4*x^2], 'clairault'] For equations involving more variables we specify independent variable:: sage: a,b,c,n=var('a b c n') sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True) [[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]] :: sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True,show_method=True) [[[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]], 'riccati'] Higher orded, not involving independent variable:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y).expand() 1/6*y(x)^3 + k1*y(x) == k2 + x :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3]).expand() 1/6*y(x)^3 - 5/3*y(x) == x - 3/2 :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3],show_method=True) [1/6*y(x)^3 - 5/3*y(x) == x - 3/2, 'freeofx'] Separable equations - Sage returns solution in implicit form:: sage: desolve(diff(y,x)*sin(y) == cos(x),y) -cos(y(x)) == c + sin(x) :: sage: desolve(diff(y,x)*sin(y) == cos(x),y,show_method=True) [-cos(y(x)) == c + sin(x), 'separable'] :: sage: desolve(diff(y,x)*sin(y) == cos(x),y,[pi/2,1]) -cos(y(x)) == sin(x) - cos(1) - 1 Linear equation - Sage returns the expression on the right hand side only:: sage: desolve(diff(y,x)+(y) == cos(x),y) 1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x) :: sage: desolve(diff(y,x)+(y) == cos(x),y,show_method=True) [1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x), 'linear'] :: sage: desolve(diff(y,x)+(y) == cos(x),y,[0,1]) 1/2*(e^x*sin(x) + e^x*cos(x) + 1)*e^(-x) This ODE with separated variables is solved as exact. Explanation - factor does not split `e^{x-y}` in Maxima into `e^{x}e^{y}`:: sage: desolve(diff(y,x)==exp(x-y),y,show_method=True) [-e^x + e^y(x) == c, 'exact'] You can solve Bessel equations. You can also use initial conditions, but you cannot put (sometimes desired) initial condition at x=0, since this point is singlar point of the equation. Anyway, if the solution should be bounded at x=0, then k2=0.:: sage: desolve(x^2*diff(y,x,x)+x*diff(y,x)+(x^2-4)*y==0,y) k1*bessel_j(2, x) + k2*bessel_y(2, x) Difficult ODE produces error:: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Difficult ODE produces error - moreover, takes a long time :: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y,contrib_ode=True) # not tested Some more types od ODE's:: sage: desolve(x*diff(y,x)^2-(1+x*y)*diff(y,x)+y==0,y,contrib_ode=True,show_method=True) [[y(x) == c + log(x), y(x) == c*e^x], 'factor'] :: sage: desolve(diff(y,x)==(x+y)^2,y,contrib_ode=True,show_method=True) [[[x == c - arctan(sqrt(t)), y(x) == -x - sqrt(t)], [x == c + arctan(sqrt(t)), y(x) == -x + sqrt(t)]], 'lagrange'] These two examples produce error (as expected, Maxima 5.18 cannot solve equations from initial conditions). Current Maxima 5.18 returns false answer in this case!:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2]).expand() # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2],show_method=True) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Second order linear ODE:: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y) (k2*x + k1)*e^(-x) + 1/2*sin(x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,show_method=True) [(k2*x + k1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1]) 1/2*(7*x + 6)*e^(-x) + 1/2*sin(x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1],show_method=True) [1/2*(7*x + 6)*e^(-x) + 1/2*sin(x), 'variationofparameters'] :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2]) 3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2],show_method=True) [3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y) (k2*x + k1)*e^(-x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,show_method=True) [(k2*x + k1)*e^(-x), 'constcoeff'] :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1]) (4*x + 3)*e^(-x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1],show_method=True) [(4*x + 3)*e^(-x), 'constcoeff'] :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2]) (2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2],show_method=True) [(2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x), 'constcoeff'] This equation can be solved within Maxima but not within Sage. It needs assumptions assume(x>0,y>0) and works in Maxima, but not in Sage:: sage: assume(x>0) # not tested sage: assume(y>0) # not tested sage: desolve(x*diff(y,x)-x*sqrt(y^2+x^2)-y,y,show_method=True) # not tested TESTS: Trac #6479 fixed:: sage: x = var('x') sage: y = function('y', x) sage: desolve( diff(y,x,x) == 0, y, [0,0,1]) x :: sage: desolve( diff(y,x,x) == 0, y, [0,1,1]) x + 1 Trac #9835 fixed:: sage: x = var('x') sage: y = function('y', x) sage: desolve(diff(y,x,2)+y*(1-y^2)==0,y,[0,-1,1,1]) Traceback (most recent call last): ... NotImplementedError: Unable to use initial condition for this equation (freeofx). AUTHORS: - David Joyner (1-2006) - Robert Bradshaw (10-2008) - Robert Marik (10-2009) """ if is_SymbolicEquation(de): de = de.lhs() - de.rhs() if is_SymbolicVariable(dvar): raise ValueError, "You have to declare dependent variable as a function, eg. y=function('y',x)" # for backwards compatibility if isinstance(dvar, list): dvar, ivar = dvar elif ivar is None: ivars = de.variables() ivars = [t for t in ivars if t is not dvar] if len(ivars) != 1: raise ValueError, "Unable to determine independent variable, please specify." ivar = ivars[0] def sanitize_var(exprs): return exprs.replace("'"+dvar_str+"("+ivar_str+")",dvar_str) de00 = de._maxima_() P = de00.parent() dvar_str=P(dvar.operator()).str() ivar_str=P(ivar).str() de00 = de00.str() de0 = sanitize_var(de00) ode_solver="ode2" cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y(x),x) soln = P(cmd) if str(soln).strip() == 'false': if contrib_ode: ode_solver="contrib_ode" P("load('contrib_ode)") cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # (TEMP:contrib_ode(x*('diff(y,x,1))^2-(x*y+1)*'diff(y,x,1)+y,y,x), if TEMP=false then TEMP else substitute(y=y(x),TEMP)) soln = P(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this ODE." else: raise NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." if show_method: maxima_method=P("method") if (ics is not None): if not is_SymbolicEquation(soln.sage()): if not show_method: maxima_method=P("method") raise NotImplementedError, "Unable to use initial condition for this equation (%s)."%(str(maxima_method).strip()) if len(ics) == 2: tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() cmd="(TEMP:ic1(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=P(cmd) if len(ics) == 3: #fixed ic2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima P("ic2_sage(soln,xa,ya,dya):=block([programmode:true,backsubst:true,singsolve:true,temp,%k2,%k1,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(dya), boundtest('%k1,%k1), boundtest('%k2,%k2), \ temp: lhs(soln) - rhs(soln), \ TEMP_k:solve([subst([xa,ya],soln), subst([dya,xa], lhs(dya)=-subst(0,lhs(dya),diff(temp,lhs(xa)))/diff(temp,lhs(ya)))],[%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)), TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") tempic=P(ivar==ics[0]).str() tempic=tempic+","+P(dvar==ics[1]).str() tempic=tempic+",'diff("+dvar_str+","+ivar_str+")="+P(ics[2]).str() cmd="(TEMP:ic2_sage(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=P(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this IVP. Remove the initial condition to get the general solution." if len(ics) == 4: #fixed bc2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima P("bc2_sage(soln,xa,ya,xb,yb):=block([programmode:true,backsubst:true,singsolve:true,temp,%k1,%k2,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(xb), noteqn(yb), boundtest('%k1,%k1), boundtest('%k2,%k2), \ TEMP_k:solve([subst([xa,ya],soln), subst([xb,yb],soln)], [%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)),TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") cmd="bc2_sage(%s(%s,%s,%s),%s,%s=%s,%s,%s=%s)"%(ode_solver,de00,dvar_str,ivar_str,P(ivar==ics[0]).str(),dvar_str,P(ics[1]).str(),P(ivar==ics[2]).str(),dvar_str,P(ics[3]).str()) cmd="(TEMP:%s,substitute(%s=%s(%s),TEMP))"%(cmd,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:bc2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,x=%pi/2,y=2),substitute(y=y(x),TEMP)) soln=P(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this BVP. Remove the initial condition to get the general solution." soln=soln.sage() if is_SymbolicEquation(soln) and soln.lhs() == dvar: # Remark: Here we do not check that the right hand side does not depend on dvar. # This probably will not hapen for soutions obtained via ode2, anyway. soln = soln.rhs() if show_method: return [soln,maxima_method.str()] else: return soln
472,324
def associated_primes(self, algorithm='sy'): r""" Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``.
def associated_primes(self, algorithm='sy'): r""" Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``.
472,325
def associated_primes(self, algorithm='sy'): r""" Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``.
def associated_primes(self, algorithm='sy'): r""" Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``.
472,326
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
@rename_keyword(deprecated='Sage version 4.6.1', l='arg') def iter_morphisms(self, arg=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
472,327
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
472,328
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
472,329
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
472,330
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
472,331
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
472,332
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
472,333
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
472,334
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
472,335
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
472,336
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
472,337
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
472,338
def cospectral_graphs(self, vertices, matrix_function=lambda g: g.adjacency_matrix(), graphs=None): """ Find all sets of graphs on ``vertices`` vertices (with possible restrictions) which are cospectral with respect to a constructed matrix.
def cospectral_graphs(self, vertices, matrix_function=lambda g: g.adjacency_matrix(), graphs=None): r""" Find all sets of graphs on ``vertices`` vertices (with possible restrictions) which are cospectral with respect to a constructed matrix.
472,339
def cospectral_graphs(self, vertices, matrix_function=lambda g: g.adjacency_matrix(), graphs=None): """ Find all sets of graphs on ``vertices`` vertices (with possible restrictions) which are cospectral with respect to a constructed matrix.
def cospectral_graphs(self, vertices, matrix_function=lambda g: g.adjacency_matrix(), graphs=None): """ Find all sets of graphs on ``vertices`` vertices (with possible restrictions) which are cospectral with respect to a constructed matrix.
472,340
def cospectral_graphs(self, vertices, matrix_function=lambda g: g.adjacency_matrix(), graphs=None): """ Find all sets of graphs on ``vertices`` vertices (with possible restrictions) which are cospectral with respect to a constructed matrix.
def cospectral_graphs(self, vertices, matrix_function=lambda g: g.adjacency_matrix(), graphs=None): """ Find all sets of graphs on ``vertices`` vertices (with possible restrictions) which are cospectral with respect to a constructed matrix.
472,341
def __call__(self, obj, output='html', view=True): r""" Return the documentation for ``obj``.
def __call__(self, obj, output='html', view=True): r""" Return the documentation for ``obj``.
472,342
def is_square(self): r""" Returns True if self is a square, and False otherwise.
def is_square(self): r""" Returns True if self is a square, and False otherwise.
472,343
def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise.
def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise.
472,344
def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise.
def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise.
472,345
def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise.
def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise.
472,346
def is_cube(self): r""" Returns True if self is a cube, and False otherwise.
def is_cube(self): r""" Returns True if self is a cube, and False otherwise.
472,347
def is_cube_free(self): r""" Returns True if self does not contain cubes, and False otherwise.
def is_cube_free(self): r""" Returns True if self does not contain cubes, and False otherwise.
472,348
def is_cube_free(self): r""" Returns True if self does not contain cubes, and False otherwise.
def is_cube_free(self): r""" Returns True if self does not contain cubes, and False otherwise.
472,349
def is_cube_free(self): r""" Returns True if self does not contain cubes, and False otherwise.
def is_cube_free(self): r""" Returns True if self does not contain cubes, and False otherwise.
472,350
def old_cremona_letter_code(n): r""" Returns the *old* Cremona letter code corresponding to an integer. integer. For example, :: 1 --> A 26 --> Z 27 --> AA 52 --> ZZ 53 --> AAA etc. INPUT: - ``n`` - int OUTPUT: str EXAMPLES:: sage: old_cremona_letter_code(1) 'A' sage: old_cremona_letter_code(26) 'Z' sage: old_cremona_letter_code(27) 'AA' sage: old_cremona_letter_code(521) 'AAAAAAAAAAAAAAAAAAAAA' sage: old_cremona_letter_code(53) 'AAA' sage: old_cremona_letter_code(2005) 'CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC' """ n -= 1 k = n%26 + 65 label = chr(k)*int(n//26 + 1) return label
def old_cremona_letter_code(n): r""" Returns the *old* Cremona letter code corresponding to an integer. integer. For example:: 1 --> A 26 --> Z 27 --> AA 52 --> ZZ 53 --> AAA etc. INPUT: - ``n`` - int OUTPUT: str EXAMPLES:: sage: old_cremona_letter_code(1) 'A' sage: old_cremona_letter_code(26) 'Z' sage: old_cremona_letter_code(27) 'AA' sage: old_cremona_letter_code(521) 'AAAAAAAAAAAAAAAAAAAAA' sage: old_cremona_letter_code(53) 'AAA' sage: old_cremona_letter_code(2005) 'CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC' """ n -= 1 k = n%26 + 65 label = chr(k)*int(n//26 + 1) return label
472,351
def __iter__(self): """ Returns an iterator through all EllipticCurve objects in the Cremona database.
def __iter__(self): """ Returns an iterator through all EllipticCurve objects in the Cremona database.
472,352
def iter(self, conductors): """ Returns an iterator through all curves with conductor between Nmin and Nmax-1, inclusive, in the database.
def iter(self, conductors): """ Returns an iterator through all curves with conductor between Nmin and Nmax-1, inclusive, in the database.
472,353
def iter_optimal(self, conductors): """ Returns an iterator through all optimal curves with conductor between Nmin and Nmax-1 in the database.
def iter_optimal(self, conductors): """ Returns an iterator through all optimal curves with conductor between Nmin and Nmax-1 in the database.
472,354
def list(self, conductors): """ Returns a list of all curves with conductor between Nmin and Nmax-1, inclusive, in the database.
def list(self, conductors): """ Returns a list of all curves with conductor between Nmin and Nmax-1, inclusive, in the database.
472,355
def list_optimal(self, conductors): """ Returns a list of all optimal curves with conductor between Nmin and Nmax-1, inclusive, in the database.
def list_optimal(self, conductors): """ Returns a list of all optimal curves with conductor between Nmin and Nmax-1, inclusive, in the database.
472,356
def smallest_conductor(self): """ The smallest conductor for which the database is complete. (Always 1.)
def smallest_conductor(self): """ The smallest conductor for which the database is complete. (Always 1.)
472,357
def conductor_range(self): """ Return the range of conductors that are covered by the database.
def conductor_range(self): """ Return the range of conductors that are covered by the database.
472,358
def _init_allgens(self, ftpdata, largest_conductor=0): """ Initialize the allgens table by reading the corresponding ftpdata files and importing them into the database. """ if self.read_only: raise RuntimeError, "The database must not be read_only." files = os.listdir(ftpdata) files.sort() name = "allgens" c = _map[name] print "Deleting old data" for N in range(1,largest_conductor+1): self[N][c] = {} self[N] = self[N] # so database knows that self[N] changed. print "Reading new data" for F in files: if not F[:len(name)] == name: continue print F for L in gzip.GzipFile(ftpdata + "/" + F).readlines(): print L v = L.split() N = int(v[0]) if largest_conductor and N > largest_conductor: self.commit() return id = v[1] + v[2] dat = [eval(s.replace(':',',')) for s in v[5:]] if not self[N].has_key(c): self[N][c] = {} self[N][c][id] = dat self[N] = self[N] # so database knows that self[N] changed.
def _init_allgens(self, ftpdata, largest_conductor=0): """ Initialize the allgens table by reading the corresponding ftpdata files and importing them into the database. """ if self.read_only: raise RuntimeError, "The database must not be read_only." files = os.listdir(ftpdata) files.sort() name = "allgens" c = _map[name] print "Deleting old data" for N in range(1,largest_conductor+1): self[N][c] = {} self[N] = self[N] # so database knows that self[N] changed. print "Reading new data" for F in files: if not F[:len(name)] == name: continue print F for L in gzip.GzipFile(ftpdata + "/" + F).readlines(): print L v = L.split() N = int(v[0]) if largest_conductor and N > largest_conductor: self.commit() return id = v[1] + v[2] dat = [eval(s.replace(':',',')) for s in v[5:]] if not self[N].has_key(c): self[N][c] = {} self[N][c][id] = dat self[N] = self[N] # so database knows that self[N] changed.
472,359
def face_lattice(self): """ Computes the face-lattice poset. Elements are tuples of (vertices, facets) - i.e. this keeps track of both the vertices in each face, and all the facets containing them.
def face_lattice(self): """ Computes the face-lattice poset. Elements are tuples of (vertices, facets) - i.e. this keeps track of both the vertices in each face, and all the facets containing them.
472,360
def library_interact(f): """ This is a decorator for using interacts in the Sage library. EXAMPLES:: sage: @interacts.decorator.library_interact ... def f(n=5): print n ... sage: f() # an interact appears <html>...</html> """ @sage_wraps(f) def library_wrapper(): # Maybe program around bug (?) in the notebook: html("</pre>") # This prints out the relevant html code to make # the interact appear: interact(f) return library_wrapper
def library_interact(f): """ This is a decorator for using interacts in the Sage library. EXAMPLES:: sage: @interacts.library.library_interact ... def f(n=5): print n ... sage: f() # an interact appears <html>...</html> """ @sage_wraps(f) def library_wrapper(): # Maybe program around bug (?) in the notebook: html("</pre>") # This prints out the relevant html code to make # the interact appear: interact(f) return library_wrapper
472,361
def demo(n=tuple(range(10)), m=tuple(range(10))): """ This is a demo interact that sums two numbers. INPUT: - `n` -- integer slider - `m` -- integer slider EXAMPLES:: sage: interacts.decorator.demo() <html>...</html> """ print n+m
def demo(n=tuple(range(10)), m=tuple(range(10))): """ This is a demo interact that sums two numbers. INPUT: - `n` -- integer slider - `m` -- integer slider EXAMPLES:: sage: interacts.library.demo() <html>...</html> """ print n+m
472,362
... def variance(self, bias = False):
... def variance(self, bias = False):
472,363
def homchain(complex=None, **kwds): r""" Compute the homology of a chain complex using the CHomP program ``homchain``. :param complex: a chain complex :param generators: if True, also return list of generators :type generators: boolean; optional, default False :param verbose: if True, print helpful messages as the computation progresses :type verbose: boolean; optional, default False :param help: if True, just print a help message and exit :type help: boolean; optional, default False :param extra_opts: options passed directly to ``homchain`` :type extra_opts: string :return: homology groups as a dictionary indexed by dimension EXAMPLES:: sage: from sage.interfaces.chomp import homchain sage: C = cubical_complexes.Sphere(3).chain_complex() sage: homchain(C)[3] # optional: need CHomP Z Generators: these are given as a list after the homology group. Each generator is specified as a cycle, an element in the appropriate free module over the base ring:: sage: C2 = delta_complexes.Sphere(2).chain_complex() sage: homchain(C2, generators=True)[2] # optional: need CHomP (Z, [(1, -1)]) sage: homchain(C2, generators=True, base_ring=GF(2))[2] (Vector space of dimension 1 over Finite Field of size 2, [(1, 1)]) TESTS: Chain complexes concentrated in negative dimensions, cochain complexes, etc.:: sage: C = ChainComplex({-5: 4 * identity_matrix(ZZ, 2)}, degree=-1) sage: homchain(C) # optional: need CHomP {-6: C4 x C4} sage: C = ChainComplex({-5: 4 * identity_matrix(ZZ, 2)}, degree=1) sage: homchain(C, generators=True) # optional: need CHomP {-4: (C4 x C4, [(1, 0), (0, 1)])} """ from sage.homology.all import ChainComplex help = kwds.get('help', False) if help: return CHomP().help('homchain') # Type-checking just in case. if isinstance(complex, ChainComplex): return CHomP()('homchain', complex, **kwds) else: raise TypeError, "Complex is not a chain complex."
def homchain(complex=None, **kwds): r""" Compute the homology of a chain complex using the CHomP program ``homchain``. :param complex: a chain complex :param generators: if True, also return list of generators :type generators: boolean; optional, default False :param verbose: if True, print helpful messages as the computation progresses :type verbose: boolean; optional, default False :param help: if True, just print a help message and exit :type help: boolean; optional, default False :param extra_opts: options passed directly to ``homchain`` :type extra_opts: string :return: homology groups as a dictionary indexed by dimension EXAMPLES:: sage: from sage.interfaces.chomp import homchain sage: C = cubical_complexes.Sphere(3).chain_complex() sage: homchain(C)[3] # optional: need CHomP Z Generators: these are given as a list after the homology group. Each generator is specified as a cycle, an element in the appropriate free module over the base ring:: sage: C2 = delta_complexes.Sphere(2).chain_complex() sage: homchain(C2, generators=True)[2] # optional: need CHomP (Z, [(1, -1)]) sage: homchain(C2, generators=True, base_ring=GF(2))[2] (Vector space of dimension 1 over Finite Field of size 2, [(1, 1)]) TESTS: Chain complexes concentrated in negative dimensions, cochain complexes, etc.:: sage: C = ChainComplex({-5: 4 * identity_matrix(ZZ, 2)}, degree=-1) sage: homchain(C) # optional: need CHomP {-6: C4 x C4} sage: C = ChainComplex({-5: 4 * identity_matrix(ZZ, 2)}, degree=1) sage: homchain(C, generators=True) # optional: need CHomP {-4: (C4 x C4, [(1, 0), (0, 1)])} """ from sage.homology.all import ChainComplex help = kwds.get('help', False) if help: return CHomP().help('homchain') # Type-checking just in case. if isinstance(complex, ChainComplex): return CHomP()('homchain', complex, **kwds) else: raise TypeError, "Complex is not a chain complex."
472,364
def __cmp__(self, right): r""" Compare ``self`` and ``right``.
def __cmp__(self, right): r""" Compare ``self`` and ``right``.
472,365
def bound_kato(self): r""" Returns a list `p` of primes such that the theorems of Kato's [Ka] and others (e.g., as explained in a paper/thesis of Grigor Grigorov [Gri]) imply that if `p` divides the order of Sha(E) then `p` is in the list.
def bound_kato(self): r""" Returns a list `p` of primes such that the theorems of Kato's [Ka] and others (e.g., as explained in a paper/thesis of Grigor Grigorov [Gri]) imply that if `p` divides the order of Sha(E) then `p` is in the list.
472,366
def bound_kato(self): r""" Returns a list `p` of primes such that the theorems of Kato's [Ka] and others (e.g., as explained in a paper/thesis of Grigor Grigorov [Gri]) imply that if `p` divides the order of Sha(E) then `p` is in the list.
def bound_kato(self): r""" Returns a list `p` of primes such that the theorems of Kato's [Ka] and others (e.g., as explained in a paper/thesis of Grigor Grigorov [Gri]) imply that if `p` divides the order of Sha(E) then `p` is in the list.
472,367
def bound_kato(self): r""" Returns a list `p` of primes such that the theorems of Kato's [Ka] and others (e.g., as explained in a paper/thesis of Grigor Grigorov [Gri]) imply that if `p` divides the order of Sha(E) then `p` is in the list.
def bound_kato(self): r""" Returns a list `p` of primes such that the theorems of Kato's [Ka] and others (e.g., as explained in a paper/thesis of Grigor Grigorov [Gri]) imply that if `p` divides the order of Sha(E) then `p` is in the list.
472,368
def bound_kato(self): r""" Returns a list `p` of primes such that the theorems of Kato's [Ka] and others (e.g., as explained in a paper/thesis of Grigor Grigorov [Gri]) imply that if `p` divides the order of Sha(E) then `p` is in the list.
def bound_kato(self): r""" Returns a list `p` of primes such that the theorems of Kato's [Ka] and others (e.g., as explained in a paper/thesis of Grigor Grigorov [Gri]) imply that if `p` divides the order of Sha(E) then `p` is in the list.
472,369
def sage_getvariablename(obj, omit_underscore_names=True): """ Attempt to get the name of a Sage object. INPUT: - ``obj`` - an object - ``omit_underscore_names`` (optional, default True) If the user has assigned an object ``obj`` to a variable name, then return that variable name. If several variables point to ``obj``, return a list of those names. If ``omit_underscore_names`` is True (the default) then omit names starting with an underscore "_". This is a modified version of code taken from http://pythonic.pocoo.org/2009/5/30/finding-objects-names, written by Georg Brandl. EXAMPLES:: sage: from sage.misc.sageinspect import sage_getvariablename sage: A = random_matrix(ZZ, 100) sage: sage_getvariablename(A) 'A' sage: B = A sage: sage_getvariablename(A) ['A', 'B'] If an object is not assigned to a variable, an empty list is returned:: sage: sage_getvariablename(random_matrix(ZZ, 60)) [] """ import gc result = [] for referrer in gc.get_referrers(obj): if isinstance(referrer, dict): for k, v in referrer.iteritems(): if v is obj: if isinstance(k, str): if (not omit_underscore_names) or not k.startswith('_'): result.append(k) if len(result) == 1: return result[0] else: return result
def sage_getvariablename(obj, omit_underscore_names=True): """ Attempt to get the name of a Sage object. INPUT: - ``obj`` - an object - ``omit_underscore_names`` (optional, default True) If the user has assigned an object ``obj`` to a variable name, then return that variable name. If several variables point to ``obj``, return a sorted list of those names. If ``omit_underscore_names`` is True (the default) then omit names starting with an underscore "_". This is a modified version of code taken from http://pythonic.pocoo.org/2009/5/30/finding-objects-names, written by Georg Brandl. EXAMPLES:: sage: from sage.misc.sageinspect import sage_getvariablename sage: A = random_matrix(ZZ, 100) sage: sage_getvariablename(A) 'A' sage: B = A sage: sage_getvariablename(A) ['A', 'B'] If an object is not assigned to a variable, an empty list is returned:: sage: sage_getvariablename(random_matrix(ZZ, 60)) [] """ import gc result = [] for referrer in gc.get_referrers(obj): if isinstance(referrer, dict): for k, v in referrer.iteritems(): if v is obj: if isinstance(k, str): if (not omit_underscore_names) or not k.startswith('_'): result.append(k) if len(result) == 1: return result[0] else: return result
472,370
def sage_getvariablename(obj, omit_underscore_names=True): """ Attempt to get the name of a Sage object. INPUT: - ``obj`` - an object - ``omit_underscore_names`` (optional, default True) If the user has assigned an object ``obj`` to a variable name, then return that variable name. If several variables point to ``obj``, return a list of those names. If ``omit_underscore_names`` is True (the default) then omit names starting with an underscore "_". This is a modified version of code taken from http://pythonic.pocoo.org/2009/5/30/finding-objects-names, written by Georg Brandl. EXAMPLES:: sage: from sage.misc.sageinspect import sage_getvariablename sage: A = random_matrix(ZZ, 100) sage: sage_getvariablename(A) 'A' sage: B = A sage: sage_getvariablename(A) ['A', 'B'] If an object is not assigned to a variable, an empty list is returned:: sage: sage_getvariablename(random_matrix(ZZ, 60)) [] """ import gc result = [] for referrer in gc.get_referrers(obj): if isinstance(referrer, dict): for k, v in referrer.iteritems(): if v is obj: if isinstance(k, str): if (not omit_underscore_names) or not k.startswith('_'): result.append(k) if len(result) == 1: return result[0] else: return result
def sage_getvariablename(obj, omit_underscore_names=True): """ Attempt to get the name of a Sage object. INPUT: - ``obj`` - an object - ``omit_underscore_names`` (optional, default True) If the user has assigned an object ``obj`` to a variable name, then return that variable name. If several variables point to ``obj``, return a list of those names. If ``omit_underscore_names`` is True (the default) then omit names starting with an underscore "_". This is a modified version of code taken from http://pythonic.pocoo.org/2009/5/30/finding-objects-names, written by Georg Brandl. EXAMPLES:: sage: from sage.misc.sageinspect import sage_getvariablename sage: A = random_matrix(ZZ, 100) sage: sage_getvariablename(A) 'A' sage: B = A sage: sage_getvariablename(A) ['A', 'B'] If an object is not assigned to a variable, an empty list is returned:: sage: sage_getvariablename(random_matrix(ZZ, 60)) [] """ import gc result = [] for referrer in gc.get_referrers(obj): if isinstance(referrer, dict): for k, v in referrer.iteritems(): if v is obj: if isinstance(k, str): if (not omit_underscore_names) or not k.startswith('_'): result.append(k) if len(result) == 1: return result[0] else: return sorted(result)
472,371
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits of `z` with ``known_bits=k`` or ``known_digits=k``. PARI is then told to compute the result using `0.8k` of these bits/digits. Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may be specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polynomial is not found, then ``None`` will be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library ``algdep`` command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
472,372
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default: ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
472,373
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default: ``False``), requires height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
472,374
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number:: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
472,375
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number:: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
472,376
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to `sqrt(2)` which is wrong in the 33'rd bit:: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
472,377
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10:: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
472,378
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion:: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
472,379
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results:: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
472,380
def is_pseudoprime_small_power(n, bound=1024, get_data=False): r""" Return True if `n` is a small power of a pseudoprime, and False otherwise. The result is *NOT* proven correct - *this IS a pseudo-primality test!*. If `get_data` is set to true and `n = p^d`, for a pseudoprime `p` and power `d`, return [(p, d)]. INPUT: - ``n`` - an integer - ``bound (default 1024)`` - int: highest power to test. - ``get_data`` - boolean: return small pseudoprime and the power. EXAMPLES:: sage: is_pseudoprime_small_power(389) True sage: is_pseudoprime_small_power(2000) False sage: is_pseudoprime_small_power(2) True sage: is_pseudoprime_small_power(1024) True sage: is_pseudoprime_small_power(-1) False sage: is_pseudoprime_small_power(1) True sage: is_pseudoprime_small_power(997^100) True The default bound is 1024:: sage: is_pseudoprime_small_power(3^1024) True sage: is_pseudoprime_small_power(3^1025) False But it can be set higher or lower:: sage: is_pseudoprime_small_power(3^1025, bound=2000) True sage: is_pseudoprime_small_power(3^100, bound=20) False Use of the get_data keyword:: sage: is_pseudoprime_small_power(3^1024, get_data=True) [(3, 1024)] sage: is_pseudoprime_small_power(2^256, get_data=True) [(2, 256)] sage: is_pseudoprime_small_power(15, get_data=True) False """ n = ZZ(n) if n.is_pseudoprime() or n == 1: return True if n < 0: return False for i in range(2, bound + 1): p, boo = n.nth_root(i, truncate_mode=True) if boo: if p.is_pseudoprime(): if get_data == True: return [(p, i)] else: return True return False
def is_pseudoprime_small_power(n, bound=1024, get_data=False): r""" Return True if `n` is a small power of a pseudoprime, and False otherwise. The result is *NOT* proven correct - *this IS a pseudo-primality test!*. If `get_data` is set to true and `n = p^d`, for a pseudoprime `p` and power `d`, return [(p, d)]. INPUT: - ``n`` - an integer - ``bound (default: 1024)`` - int: highest power to test. - ``get_data`` - boolean: return small pseudoprime and the power. EXAMPLES:: sage: is_pseudoprime_small_power(389) True sage: is_pseudoprime_small_power(2000) False sage: is_pseudoprime_small_power(2) True sage: is_pseudoprime_small_power(1024) True sage: is_pseudoprime_small_power(-1) False sage: is_pseudoprime_small_power(1) True sage: is_pseudoprime_small_power(997^100) True The default bound is 1024:: sage: is_pseudoprime_small_power(3^1024) True sage: is_pseudoprime_small_power(3^1025) False But it can be set higher or lower:: sage: is_pseudoprime_small_power(3^1025, bound=2000) True sage: is_pseudoprime_small_power(3^100, bound=20) False Use of the get_data keyword:: sage: is_pseudoprime_small_power(3^1024, get_data=True) [(3, 1024)] sage: is_pseudoprime_small_power(2^256, get_data=True) [(2, 256)] sage: is_pseudoprime_small_power(15, get_data=True) False """ n = ZZ(n) if n.is_pseudoprime() or n == 1: return True if n < 0: return False for i in range(2, bound + 1): p, boo = n.nth_root(i, truncate_mode=True) if boo: if p.is_pseudoprime(): if get_data == True: return [(p, i)] else: return True return False
472,381
def factor(n, proof=None, int_=False, algorithm='pari', verbose=0, **kwds): """ Returns the factorization of n. The result depends on the type of n. If n is an integer, factor returns the factorization of the integer n as an object of type Factorization. If n is not an integer, ``n.factor(proof=proof, **kwds)`` gets called. See ``n.factor??`` for more documentation in this case. .. warning:: This means that applying factor to an integer result of a symbolic computation will not factor the integer, because it is considered as an element of a larger symbolic ring. EXAMPLE:: sage: f(n)=n^2 sage: is_prime(f(3)) False sage: factor(f(3)) 9 INPUT: - ``n`` - an nonzero integer - ``proof`` - bool or None (default: None) - ``int_`` - bool (default: False) whether to return answers as Python ints - ``algorithm`` - string - ``'pari'`` - (default) use the PARI c library - ``'kash'`` - use KASH computer algebra system (requires the optional kash package be installed) - ``'magma'`` - use Magma (requires magma be installed) - ``verbose`` - integer (default 0); pari's debug variable is set to this; e.g., set to 4 or 8 to see lots of output during factorization. OUTPUT: factorization of n The qsieve and ecm commands give access to highly optimized implementations of algorithms for doing certain integer factorization problems. These implementations are not used by the generic factor command, which currently just calls PARI (note that PARI also implements sieve and ecm algorithms, but they aren't as optimized). Thus you might consider using them instead for certain numbers. The factorization returned is an element of the class :class:`~sage.structure.factorization.Factorization`; see Factorization?? for more details, and examples below for usage. A Factorization contains both the unit factor (+1 or -1) and a sorted list of (prime, exponent) pairs. The factorization displays in pretty-print format but it is easy to obtain access to the (prime,exponent) pairs and the unit, to recover the number from its factorization, and even to multiply two factorizations. See examples below. EXAMPLES:: sage: factor(500) 2^2 * 5^3 sage: factor(-20) -1 * 2^2 * 5 sage: f=factor(-20) sage: list(f) [(2, 2), (5, 1)] sage: f.unit() -1 sage: f.value() -20 sage: factor( -next_prime(10^2) * next_prime(10^7) ) -1 * 101 * 10000019 :: sage: factor(-500, algorithm='kash') # optional - kash -1 * 2^2 * 5^3 :: sage: factor(-500, algorithm='magma') # optional - magma -1 * 2^2 * 5^3 :: sage: factor(0) Traceback (most recent call last): ... ArithmeticError: Prime factorization of 0 not defined. sage: factor(1) 1 sage: factor(-1) -1 sage: factor(2^(2^7)+1) 59649589127497217 * 5704689200685129054721 Sage calls PARI's factor, which has proof False by default. Sage has a global proof flag, set to True by default (see :mod:`sage.structure.proof.proof`, or proof.[tab]). To override the default, call this function with proof=False. :: sage: factor(3^89-1, proof=False) 2 * 179 * 1611479891519807 * 5042939439565996049162197 :: sage: factor(2^197 + 1) # takes a long time (e.g., 3 seconds!) 3 * 197002597249 * 1348959352853811313 * 251951573867253012259144010843 Any object which has a factor method can be factored like this:: sage: K.<i> = QuadraticField(-1) sage: factor(122+454*i) (-1) * (-2*i - 3) * (-i + 4) * (i + 1)^3 * (-i + 2)^3 To access the data in a factorization:: sage: f = factor(420); f 2^2 * 3 * 5 * 7 sage: [x for x in f] [(2, 2), (3, 1), (5, 1), (7, 1)] sage: [p for p,e in f] [2, 3, 5, 7] sage: [e for p,e in f] [2, 1, 1, 1] sage: [p^e for p,e in f] [4, 3, 5, 7] """ if not isinstance(n, (int,long, integer.Integer)): # this happens for example if n = x**2 + y**2 + 2*x*y try: return n.factor(proof=proof, **kwds) except AttributeError: raise TypeError, "unable to factor n" except TypeError: # just in case factor method doesn't have a proof option. try: return n.factor(**kwds) except AttributeError: raise TypeError, "unable to factor n" #n = abs(n) n = ZZ(n) if n < 0: unit = ZZ(-1) n = -n else: unit = ZZ(1) if n == 0: raise ArithmeticError, "Prime factorization of 0 not defined." if n == 1: return factorization.Factorization([], unit) if n < 10000000000000: return factorization.Factorization(__factor_using_trial_division(n), unit) if algorithm == 'pari': return factorization.Factorization(__factor_using_pari(n, int_=int_, debug_level=verbose, proof=proof), unit) elif algorithm in ['kash', 'magma']: if algorithm == 'kash': from sage.interfaces.all import kash as I else: from sage.interfaces.all import magma as I F = I.eval('Factorization(%s)'%n) i = F.rfind(']') + 1 F = F[:i] F = F.replace("<","(").replace(">",")") F = eval(F) if not int_: F = [(ZZ(a), ZZ(b)) for a,b in F] return factorization.Factorization(F, unit) else: raise ValueError, "Algorithm is not known"
def factor(n, proof=None, int_=False, algorithm='pari', verbose=0, **kwds): """ Returns the factorization of n. The result depends on the type of n. If n is an integer, factor returns the factorization of the integer n as an object of type Factorization. If n is not an integer, ``n.factor(proof=proof, **kwds)`` gets called. See ``n.factor??`` for more documentation in this case. .. warning:: This means that applying factor to an integer result of a symbolic computation will not factor the integer, because it is considered as an element of a larger symbolic ring. EXAMPLE:: sage: f(n)=n^2 sage: is_prime(f(3)) False sage: factor(f(3)) 9 INPUT: - ``n`` - an nonzero integer - ``proof`` - bool or None (default: None) - ``int_`` - bool (default: False) whether to return answers as Python ints - ``algorithm`` - string - ``'pari'`` - (default) use the PARI c library - ``'kash'`` - use KASH computer algebra system (requires the optional kash package be installed) - ``'magma'`` - use Magma (requires magma be installed) - ``verbose`` - integer (default: 0); PARI's debug variable is set to this; e.g., set to 4 or 8 to see lots of output during factorization. OUTPUT: factorization of n The qsieve and ecm commands give access to highly optimized implementations of algorithms for doing certain integer factorization problems. These implementations are not used by the generic factor command, which currently just calls PARI (note that PARI also implements sieve and ecm algorithms, but they aren't as optimized). Thus you might consider using them instead for certain numbers. The factorization returned is an element of the class :class:`~sage.structure.factorization.Factorization`; see Factorization?? for more details, and examples below for usage. A Factorization contains both the unit factor (+1 or -1) and a sorted list of (prime, exponent) pairs. The factorization displays in pretty-print format but it is easy to obtain access to the (prime,exponent) pairs and the unit, to recover the number from its factorization, and even to multiply two factorizations. See examples below. EXAMPLES:: sage: factor(500) 2^2 * 5^3 sage: factor(-20) -1 * 2^2 * 5 sage: f=factor(-20) sage: list(f) [(2, 2), (5, 1)] sage: f.unit() -1 sage: f.value() -20 sage: factor( -next_prime(10^2) * next_prime(10^7) ) -1 * 101 * 10000019 :: sage: factor(-500, algorithm='kash') # optional - kash -1 * 2^2 * 5^3 :: sage: factor(-500, algorithm='magma') # optional - magma -1 * 2^2 * 5^3 :: sage: factor(0) Traceback (most recent call last): ... ArithmeticError: Prime factorization of 0 not defined. sage: factor(1) 1 sage: factor(-1) -1 sage: factor(2^(2^7)+1) 59649589127497217 * 5704689200685129054721 Sage calls PARI's factor, which has proof False by default. Sage has a global proof flag, set to True by default (see :mod:`sage.structure.proof.proof`, or proof.[tab]). To override the default, call this function with proof=False. :: sage: factor(3^89-1, proof=False) 2 * 179 * 1611479891519807 * 5042939439565996049162197 :: sage: factor(2^197 + 1) # takes a long time (e.g., 3 seconds!) 3 * 197002597249 * 1348959352853811313 * 251951573867253012259144010843 Any object which has a factor method can be factored like this:: sage: K.<i> = QuadraticField(-1) sage: factor(122+454*i) (-1) * (-2*i - 3) * (-i + 4) * (i + 1)^3 * (-i + 2)^3 To access the data in a factorization:: sage: f = factor(420); f 2^2 * 3 * 5 * 7 sage: [x for x in f] [(2, 2), (3, 1), (5, 1), (7, 1)] sage: [p for p,e in f] [2, 3, 5, 7] sage: [e for p,e in f] [2, 1, 1, 1] sage: [p^e for p,e in f] [4, 3, 5, 7] """ if not isinstance(n, (int,long, integer.Integer)): # this happens for example if n = x**2 + y**2 + 2*x*y try: return n.factor(proof=proof, **kwds) except AttributeError: raise TypeError, "unable to factor n" except TypeError: # just in case factor method doesn't have a proof option. try: return n.factor(**kwds) except AttributeError: raise TypeError, "unable to factor n" #n = abs(n) n = ZZ(n) if n < 0: unit = ZZ(-1) n = -n else: unit = ZZ(1) if n == 0: raise ArithmeticError, "Prime factorization of 0 not defined." if n == 1: return factorization.Factorization([], unit) if n < 10000000000000: return factorization.Factorization(__factor_using_trial_division(n), unit) if algorithm == 'pari': return factorization.Factorization(__factor_using_pari(n, int_=int_, debug_level=verbose, proof=proof), unit) elif algorithm in ['kash', 'magma']: if algorithm == 'kash': from sage.interfaces.all import kash as I else: from sage.interfaces.all import magma as I F = I.eval('Factorization(%s)'%n) i = F.rfind(']') + 1 F = F[:i] F = F.replace("<","(").replace(">",")") F = eval(F) if not int_: F = [(ZZ(a), ZZ(b)) for a,b in F] return factorization.Factorization(F, unit) else: raise ValueError, "Algorithm is not known"
472,382
def desolve(de, dvar, ics=None, ivar=None, show_method=False, contrib_ode=False): """ Solves a 1st or 2nd order linear ODE via maxima. Including IVP and BVP. *Use* ``desolve? <tab>`` *if the output in truncated in notebook.* INPUT: - ``de`` - an expression or equation representing the ODE - ``dvar`` - the dependent variable (hereafter called ``y``) - ``ics`` - (optional) the initial or boundary conditions - for a first-order equation, specify the initial ``x`` and ``y`` - for a second-order equation, specify the initial ``x``, ``y``, and ``dy/dx`` - for a second-order boundary solution, specify initial and final ``x`` and ``y`` initial conditions gives error if the solution is not SymbolisEquation (as happens for example for clairot equation) - ``ivar`` - (optional) the independent variable (hereafter called x), which must be specified if there is more than one independent variable in the equation. - ``show_method`` - (optional) if true, then Sage returns pair ``[solution, method]``, where method is the string describing method which has been used to get solution (Maxima uses the following order for first order equations: linear, separable, exact (including exact with integrating factor), homogeneous, bernoulli, generalized homogeneous) - use carefully in class, see below for the example of the equation which is separable but this property is not recognized by Maxima and equation is solved as exact. - ``contrib_ode`` - (optional) if true, desolve allows to solve clairot, lagrange, riccati and some other equations. May take a long time and thus turned off by default. Initial conditions can be used only if the result is one SymbolicEquation (does not contain singular solution, for example) OUTPUT: In most cases returns SymbolicEquation which defines the solution implicitly. If the result is in the form y(x)=... (happens for linear eqs.), returns the right-hand side only. The possible constant solutions of separable ODE's are omitted. EXAMPLES:: sage: x = var('x') sage: y = function('y', x) sage: desolve(diff(y,x) + y - 1, y) (c + e^x)*e^(-x) :: sage: f = desolve(diff(y,x) + y - 1, y, ics=[10,2]); f (e^10 + e^x)*e^(-x) :: sage: plot(f) We can also solve second-order differential equations.:: sage: x = var('x') sage: y = function('y', x) sage: de = diff(y,x,2) - y == x sage: desolve(de, y) k1*e^x + k2*e^(-x) - x :: sage: f = desolve(de, y, [10,2,1]); f -x + 5*e^(-x + 10) + 7*e^(x - 10) sage: f(x=10) 2 sage: diff(f,x)(x=10) 1 :: sage: de = diff(y,x,2) + y == 0 sage: desolve(de, y) k1*sin(x) + k2*cos(x) sage: desolve(de, y, [0,1,pi/2,4]) 4*sin(x) + cos(x) sage: desolve(y*diff(y,x)+sin(x)==0,y) -1/2*y(x)^2 == c - cos(x) Clairot equation: general and singular solutions:: sage: desolve(diff(y,x)^2+x*diff(y,x)-y==0,y,contrib_ode=True,show_method=True) [[y(x) == c^2 + c*x, y(x) == -1/4*x^2], 'clairault'] For equations involving more variables we specify independent variable:: sage: a,b,c,n=var('a b c n') sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True) [[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]] sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True,show_method=True) [[[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]], 'riccati'] Higher orded, not involving independent variable:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y).expand() 1/6*y(x)^3 + k1*y(x) == k2 + x sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3]).expand() 1/6*y(x)^3 - 5/3*y(x) == x - 3/2 sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3],show_method=True) [1/6*y(x)^3 - 5/3*y(x) == x - 3/2, 'freeofx'] Separable equations - Sage returns solution in implicit form:: sage: desolve(diff(y,x)*sin(y) == cos(x),y) -cos(y(x)) == c + sin(x) sage: desolve(diff(y,x)*sin(y) == cos(x),y,show_method=True) [-cos(y(x)) == c + sin(x), 'separable'] sage: desolve(diff(y,x)*sin(y) == cos(x),y,[pi/2,1]) -cos(y(x)) == sin(x) - cos(1) - 1 Linear equation - Sage returns the expression on the right hand side only:: sage: desolve(diff(y,x)+(y) == cos(x),y) 1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x) sage: desolve(diff(y,x)+(y) == cos(x),y,show_method=True) [1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x), 'linear'] sage: desolve(diff(y,x)+(y) == cos(x),y,[0,1]) 1/2*(e^x*sin(x) + e^x*cos(x) + 1)*e^(-x) This ODE with separated variables is solved as exact. Explanation - factor does not split `e^{x-y}` in Maxima into `e^{x}e^{y}`:: sage: desolve(diff(y,x)==exp(x-y),y,show_method=True) [-e^x + e^y(x) == c, 'exact'] You can solve Bessel equations. You can also use initial conditions, but you cannot put (sometimes desired) initial condition at x=0, since this point is singlar point of the equation. Anyway, if the solution should be bounded at x=0, then k2=0.:: sage: desolve(x^2*diff(y,x,x)+x*diff(y,x)+(x^2-4)*y==0,y) k1*bessel_j(2, x) + k2*bessel_y(2, x) Difficult ODE produces error:: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Difficult ODE produces error - moreover, takes a long time :: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y,contrib_ode=True) # not tested Some more types od ODE's:: sage: desolve(x*diff(y,x)^2-(1+x*y)*diff(y,x)+y==0,y,contrib_ode=True,show_method=True) [[y(x) == c + log(x), y(x) == c*e^x], 'factor'] :: sage: desolve(diff(y,x)==(x+y)^2,y,contrib_ode=True,show_method=True) [[[x == c - arctan(sqrt(t)), y(x) == -x - sqrt(t)], [x == c + arctan(sqrt(t)), y(x) == -x + sqrt(t)]], 'lagrange'] These two examples produce error (as expected, Maxima 5.18 cannot solve equations from initial conditions). Current Maxima 5.18 returns false answer in this case!:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2]).expand() # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2],show_method=True) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Second order linear ODE:: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y) (k2*x + k1)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,show_method=True) [(k2*x + k1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1]) 1/2*(7*x + 6)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1],show_method=True) [1/2*(7*x + 6)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2]) 3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2],show_method=True) [3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y) (k2*x + k1)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,show_method=True) [(k2*x + k1)*e^(-x), 'constcoeff'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1]) (4*x + 3)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1],show_method=True) [(4*x + 3)*e^(-x), 'constcoeff'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2]) (2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2],show_method=True) [(2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x), 'constcoeff'] This equation can be solved within Maxima but not within Sage. It needs assumptions assume(x>0,y>0) and works in Maxima, but not in Sage:: sage: assume(x>0) # not tested sage: assume(y>0) # not tested sage: desolve(x*diff(y,x)-x*sqrt(y^2+x^2)-y,y,show_method=True) # not tested TESTS: Trac #6479 fixed:: sage: x = var('x') sage: y = function('y', x) sage: desolve( diff(y,x,x) == 0, y, [0,0,1]) x :: sage: desolve( diff(y,x,x) == 0, y, [0,1,1]) x + 1 AUTHORS: - David Joyner (1-2006) - Robert Bradshaw (10-2008) - Robert Marik (10-2009) """ if is_SymbolicEquation(de): de = de.lhs() - de.rhs() if is_SymbolicVariable(dvar): raise ValueError, "You have to declare dependent variable as a function, eg. y=function('y',x)" # for backwards compatibility if isinstance(dvar, list): dvar, ivar = dvar elif ivar is None: ivars = de.variables() ivars = [t for t in ivars if t is not dvar] if len(ivars) != 1: raise ValueError, "Unable to determine independent variable, please specify." ivar = ivars[0] def sanitize_var(exprs): return exprs.replace("'"+dvar_str+"("+ivar_str+")",dvar_str) dvar_str=dvar.operator()._maxima_().str() ivar_str=ivar._maxima_().str() de00 = de._maxima_().str() de0 = sanitize_var(de00) ode_solver="ode2" cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y(x),x) soln = maxima(cmd) if str(soln).strip() == 'false': if contrib_ode: ode_solver="contrib_ode" maxima("load('contrib_ode)") cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # (TEMP:contrib_ode(x*('diff(y,x,1))^2-(x*y+1)*'diff(y,x,1)+y,y,x), if TEMP=false then TEMP else substitute(y=y(x),TEMP)) soln = maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this ODE." else: raise NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." if show_method: maxima_method=maxima("method") if (ics is not None): if not is_SymbolicEquation(soln.sage()): raise NotImplementedError, "Maxima was unable to use initial condition for this equation (%s)"%(maxima_method.str()) if len(ics) == 2: tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() cmd="(TEMP:ic1(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=maxima(cmd) if len(ics) == 3: #fixed ic2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima maxima("ic2_sage(soln,xa,ya,dya):=block([programmode:true,backsubst:true,singsolve:true,temp,%k2,%k1,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(dya), boundtest('%k1,%k1), boundtest('%k2,%k2), \ temp: lhs(soln) - rhs(soln), \ TEMP_k:solve([subst([xa,ya],soln), subst([dya,xa], lhs(dya)=-subst(0,lhs(dya),diff(temp,lhs(xa)))/diff(temp,lhs(ya)))],[%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)), TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() tempic=tempic+",'diff("+dvar_str+","+ivar_str+")="+(ics[2])._maxima_().str() cmd="(TEMP:ic2_sage(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this IVP. Remove the initial contition to get the general solution." if len(ics) == 4: #fixed bc2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima maxima("bc2_sage(soln,xa,ya,xb,yb):=block([programmode:true,backsubst:true,singsolve:true,temp,%k1,%k2,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(xb), noteqn(yb), boundtest('%k1,%k1), boundtest('%k2,%k2), \ TEMP_k:solve([subst([xa,ya],soln), subst([xb,yb],soln)], [%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)),TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") cmd="bc2_sage(%s(%s,%s,%s),%s,%s=%s,%s,%s=%s)"%(ode_solver,de00,dvar_str,ivar_str,(ivar==ics[0])._maxima_().str(),dvar_str,(ics[1])._maxima_().str(),(ivar==ics[2])._maxima_().str(),dvar_str,(ics[3])._maxima_().str()) cmd="(TEMP:%s,substitute(%s=%s(%s),TEMP))"%(cmd,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:bc2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,x=%pi/2,y=2),substitute(y=y(x),TEMP)) soln=maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this BVP. Remove the initial contition to get the general solution." soln=soln.sage() if is_SymbolicEquation(soln) and soln.lhs() == dvar: # Remark: Here we do not check that the right hand side does not depend on dvar. # This probably will not hapen for soutions obtained via ode2, anyway. soln = soln.rhs() if show_method: return [soln,maxima_method.str()] else: return soln
def desolve(de, dvar, ics=None, ivar=None, show_method=False, contrib_ode=False): """ Solves a 1st or 2nd order linear ODE via maxima. Including IVP and BVP. *Use* ``desolve? <tab>`` *if the output in truncated in notebook.* INPUT: - ``de`` - an expression or equation representing the ODE - ``dvar`` - the dependent variable (hereafter called ``y``) - ``ics`` - (optional) the initial or boundary conditions - for a first-order equation, specify the initial ``x`` and ``y`` - for a second-order equation, specify the initial ``x``, ``y``, and ``dy/dx`` - for a second-order boundary solution, specify initial and final ``x`` and ``y`` initial conditions gives error if the solution is not SymbolicEquation (as happens for example for clairot equation) - ``ivar`` - (optional) the independent variable (hereafter called x), which must be specified if there is more than one independent variable in the equation. - ``show_method`` - (optional) if true, then Sage returns pair ``[solution, method]``, where method is the string describing method which has been used to get solution (Maxima uses the following order for first order equations: linear, separable, exact (including exact with integrating factor), homogeneous, bernoulli, generalized homogeneous) - use carefully in class, see below for the example of the equation which is separable but this property is not recognized by Maxima and equation is solved as exact. - ``contrib_ode`` - (optional) if true, desolve allows to solve clairot, lagrange, riccati and some other equations. May take a long time and thus turned off by default. Initial conditions can be used only if the result is one SymbolicEquation (does not contain singular solution, for example) OUTPUT: In most cases returns SymbolicEquation which defines the solution implicitly. If the result is in the form y(x)=... (happens for linear eqs.), returns the right-hand side only. The possible constant solutions of separable ODE's are omitted. EXAMPLES:: sage: x = var('x') sage: y = function('y', x) sage: desolve(diff(y,x) + y - 1, y) (c + e^x)*e^(-x) :: sage: f = desolve(diff(y,x) + y - 1, y, ics=[10,2]); f (e^10 + e^x)*e^(-x) :: sage: plot(f) We can also solve second-order differential equations.:: sage: x = var('x') sage: y = function('y', x) sage: de = diff(y,x,2) - y == x sage: desolve(de, y) k1*e^x + k2*e^(-x) - x :: sage: f = desolve(de, y, [10,2,1]); f -x + 5*e^(-x + 10) + 7*e^(x - 10) sage: f(x=10) 2 sage: diff(f,x)(x=10) 1 :: sage: de = diff(y,x,2) + y == 0 sage: desolve(de, y) k1*sin(x) + k2*cos(x) sage: desolve(de, y, [0,1,pi/2,4]) 4*sin(x) + cos(x) sage: desolve(y*diff(y,x)+sin(x)==0,y) -1/2*y(x)^2 == c - cos(x) Clairot equation: general and singular solutions:: sage: desolve(diff(y,x)^2+x*diff(y,x)-y==0,y,contrib_ode=True,show_method=True) [[y(x) == c^2 + c*x, y(x) == -1/4*x^2], 'clairault'] For equations involving more variables we specify independent variable:: sage: a,b,c,n=var('a b c n') sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True) [[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]] sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True,show_method=True) [[[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]], 'riccati'] Higher orded, not involving independent variable:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y).expand() 1/6*y(x)^3 + k1*y(x) == k2 + x sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3]).expand() 1/6*y(x)^3 - 5/3*y(x) == x - 3/2 sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3],show_method=True) [1/6*y(x)^3 - 5/3*y(x) == x - 3/2, 'freeofx'] Separable equations - Sage returns solution in implicit form:: sage: desolve(diff(y,x)*sin(y) == cos(x),y) -cos(y(x)) == c + sin(x) sage: desolve(diff(y,x)*sin(y) == cos(x),y,show_method=True) [-cos(y(x)) == c + sin(x), 'separable'] sage: desolve(diff(y,x)*sin(y) == cos(x),y,[pi/2,1]) -cos(y(x)) == sin(x) - cos(1) - 1 Linear equation - Sage returns the expression on the right hand side only:: sage: desolve(diff(y,x)+(y) == cos(x),y) 1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x) sage: desolve(diff(y,x)+(y) == cos(x),y,show_method=True) [1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x), 'linear'] sage: desolve(diff(y,x)+(y) == cos(x),y,[0,1]) 1/2*(e^x*sin(x) + e^x*cos(x) + 1)*e^(-x) This ODE with separated variables is solved as exact. Explanation - factor does not split `e^{x-y}` in Maxima into `e^{x}e^{y}`:: sage: desolve(diff(y,x)==exp(x-y),y,show_method=True) [-e^x + e^y(x) == c, 'exact'] You can solve Bessel equations. You can also use initial conditions, but you cannot put (sometimes desired) initial condition at x=0, since this point is singlar point of the equation. Anyway, if the solution should be bounded at x=0, then k2=0.:: sage: desolve(x^2*diff(y,x,x)+x*diff(y,x)+(x^2-4)*y==0,y) k1*bessel_j(2, x) + k2*bessel_y(2, x) Difficult ODE produces error:: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Difficult ODE produces error - moreover, takes a long time :: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y,contrib_ode=True) # not tested Some more types od ODE's:: sage: desolve(x*diff(y,x)^2-(1+x*y)*diff(y,x)+y==0,y,contrib_ode=True,show_method=True) [[y(x) == c + log(x), y(x) == c*e^x], 'factor'] :: sage: desolve(diff(y,x)==(x+y)^2,y,contrib_ode=True,show_method=True) [[[x == c - arctan(sqrt(t)), y(x) == -x - sqrt(t)], [x == c + arctan(sqrt(t)), y(x) == -x + sqrt(t)]], 'lagrange'] These two examples produce error (as expected, Maxima 5.18 cannot solve equations from initial conditions). Current Maxima 5.18 returns false answer in this case!:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2]).expand() # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2],show_method=True) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Second order linear ODE:: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y) (k2*x + k1)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,show_method=True) [(k2*x + k1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1]) 1/2*(7*x + 6)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1],show_method=True) [1/2*(7*x + 6)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2]) 3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2],show_method=True) [3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y) (k2*x + k1)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,show_method=True) [(k2*x + k1)*e^(-x), 'constcoeff'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1]) (4*x + 3)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1],show_method=True) [(4*x + 3)*e^(-x), 'constcoeff'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2]) (2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2],show_method=True) [(2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x), 'constcoeff'] This equation can be solved within Maxima but not within Sage. It needs assumptions assume(x>0,y>0) and works in Maxima, but not in Sage:: sage: assume(x>0) # not tested sage: assume(y>0) # not tested sage: desolve(x*diff(y,x)-x*sqrt(y^2+x^2)-y,y,show_method=True) # not tested TESTS: Trac #6479 fixed:: sage: x = var('x') sage: y = function('y', x) sage: desolve( diff(y,x,x) == 0, y, [0,0,1]) x :: sage: desolve( diff(y,x,x) == 0, y, [0,1,1]) x + 1 AUTHORS: - David Joyner (1-2006) - Robert Bradshaw (10-2008) - Robert Marik (10-2009) """ if is_SymbolicEquation(de): de = de.lhs() - de.rhs() if is_SymbolicVariable(dvar): raise ValueError, "You have to declare dependent variable as a function, eg. y=function('y',x)" # for backwards compatibility if isinstance(dvar, list): dvar, ivar = dvar elif ivar is None: ivars = de.variables() ivars = [t for t in ivars if t is not dvar] if len(ivars) != 1: raise ValueError, "Unable to determine independent variable, please specify." ivar = ivars[0] def sanitize_var(exprs): return exprs.replace("'"+dvar_str+"("+ivar_str+")",dvar_str) dvar_str=dvar.operator()._maxima_().str() ivar_str=ivar._maxima_().str() de00 = de._maxima_().str() de0 = sanitize_var(de00) ode_solver="ode2" cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y(x),x) soln = maxima(cmd) if str(soln).strip() == 'false': if contrib_ode: ode_solver="contrib_ode" maxima("load('contrib_ode)") cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # (TEMP:contrib_ode(x*('diff(y,x,1))^2-(x*y+1)*'diff(y,x,1)+y,y,x), if TEMP=false then TEMP else substitute(y=y(x),TEMP)) soln = maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this ODE." else: raise NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." if show_method: maxima_method=maxima("method") if (ics is not None): if not is_SymbolicEquation(soln.sage()): raise NotImplementedError, "Maxima was unable to use initial condition for this equation (%s)"%(maxima_method.str()) if len(ics) == 2: tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() cmd="(TEMP:ic1(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=maxima(cmd) if len(ics) == 3: #fixed ic2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima maxima("ic2_sage(soln,xa,ya,dya):=block([programmode:true,backsubst:true,singsolve:true,temp,%k2,%k1,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(dya), boundtest('%k1,%k1), boundtest('%k2,%k2), \ temp: lhs(soln) - rhs(soln), \ TEMP_k:solve([subst([xa,ya],soln), subst([dya,xa], lhs(dya)=-subst(0,lhs(dya),diff(temp,lhs(xa)))/diff(temp,lhs(ya)))],[%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)), TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() tempic=tempic+",'diff("+dvar_str+","+ivar_str+")="+(ics[2])._maxima_().str() cmd="(TEMP:ic2_sage(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this IVP. Remove the initial contition to get the general solution." if len(ics) == 4: #fixed bc2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima maxima("bc2_sage(soln,xa,ya,xb,yb):=block([programmode:true,backsubst:true,singsolve:true,temp,%k1,%k2,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(xb), noteqn(yb), boundtest('%k1,%k1), boundtest('%k2,%k2), \ TEMP_k:solve([subst([xa,ya],soln), subst([xb,yb],soln)], [%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)),TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") cmd="bc2_sage(%s(%s,%s,%s),%s,%s=%s,%s,%s=%s)"%(ode_solver,de00,dvar_str,ivar_str,(ivar==ics[0])._maxima_().str(),dvar_str,(ics[1])._maxima_().str(),(ivar==ics[2])._maxima_().str(),dvar_str,(ics[3])._maxima_().str()) cmd="(TEMP:%s,substitute(%s=%s(%s),TEMP))"%(cmd,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:bc2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,x=%pi/2,y=2),substitute(y=y(x),TEMP)) soln=maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this BVP. Remove the initial contition to get the general solution." soln=soln.sage() if is_SymbolicEquation(soln) and soln.lhs() == dvar: # Remark: Here we do not check that the right hand side does not depend on dvar. # This probably will not hapen for soutions obtained via ode2, anyway. soln = soln.rhs() if show_method: return [soln,maxima_method.str()] else: return soln
472,383
def desolve(de, dvar, ics=None, ivar=None, show_method=False, contrib_ode=False): """ Solves a 1st or 2nd order linear ODE via maxima. Including IVP and BVP. *Use* ``desolve? <tab>`` *if the output in truncated in notebook.* INPUT: - ``de`` - an expression or equation representing the ODE - ``dvar`` - the dependent variable (hereafter called ``y``) - ``ics`` - (optional) the initial or boundary conditions - for a first-order equation, specify the initial ``x`` and ``y`` - for a second-order equation, specify the initial ``x``, ``y``, and ``dy/dx`` - for a second-order boundary solution, specify initial and final ``x`` and ``y`` initial conditions gives error if the solution is not SymbolisEquation (as happens for example for clairot equation) - ``ivar`` - (optional) the independent variable (hereafter called x), which must be specified if there is more than one independent variable in the equation. - ``show_method`` - (optional) if true, then Sage returns pair ``[solution, method]``, where method is the string describing method which has been used to get solution (Maxima uses the following order for first order equations: linear, separable, exact (including exact with integrating factor), homogeneous, bernoulli, generalized homogeneous) - use carefully in class, see below for the example of the equation which is separable but this property is not recognized by Maxima and equation is solved as exact. - ``contrib_ode`` - (optional) if true, desolve allows to solve clairot, lagrange, riccati and some other equations. May take a long time and thus turned off by default. Initial conditions can be used only if the result is one SymbolicEquation (does not contain singular solution, for example) OUTPUT: In most cases returns SymbolicEquation which defines the solution implicitly. If the result is in the form y(x)=... (happens for linear eqs.), returns the right-hand side only. The possible constant solutions of separable ODE's are omitted. EXAMPLES:: sage: x = var('x') sage: y = function('y', x) sage: desolve(diff(y,x) + y - 1, y) (c + e^x)*e^(-x) :: sage: f = desolve(diff(y,x) + y - 1, y, ics=[10,2]); f (e^10 + e^x)*e^(-x) :: sage: plot(f) We can also solve second-order differential equations.:: sage: x = var('x') sage: y = function('y', x) sage: de = diff(y,x,2) - y == x sage: desolve(de, y) k1*e^x + k2*e^(-x) - x :: sage: f = desolve(de, y, [10,2,1]); f -x + 5*e^(-x + 10) + 7*e^(x - 10) sage: f(x=10) 2 sage: diff(f,x)(x=10) 1 :: sage: de = diff(y,x,2) + y == 0 sage: desolve(de, y) k1*sin(x) + k2*cos(x) sage: desolve(de, y, [0,1,pi/2,4]) 4*sin(x) + cos(x) sage: desolve(y*diff(y,x)+sin(x)==0,y) -1/2*y(x)^2 == c - cos(x) Clairot equation: general and singular solutions:: sage: desolve(diff(y,x)^2+x*diff(y,x)-y==0,y,contrib_ode=True,show_method=True) [[y(x) == c^2 + c*x, y(x) == -1/4*x^2], 'clairault'] For equations involving more variables we specify independent variable:: sage: a,b,c,n=var('a b c n') sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True) [[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]] sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True,show_method=True) [[[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]], 'riccati'] Higher orded, not involving independent variable:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y).expand() 1/6*y(x)^3 + k1*y(x) == k2 + x sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3]).expand() 1/6*y(x)^3 - 5/3*y(x) == x - 3/2 sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3],show_method=True) [1/6*y(x)^3 - 5/3*y(x) == x - 3/2, 'freeofx'] Separable equations - Sage returns solution in implicit form:: sage: desolve(diff(y,x)*sin(y) == cos(x),y) -cos(y(x)) == c + sin(x) sage: desolve(diff(y,x)*sin(y) == cos(x),y,show_method=True) [-cos(y(x)) == c + sin(x), 'separable'] sage: desolve(diff(y,x)*sin(y) == cos(x),y,[pi/2,1]) -cos(y(x)) == sin(x) - cos(1) - 1 Linear equation - Sage returns the expression on the right hand side only:: sage: desolve(diff(y,x)+(y) == cos(x),y) 1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x) sage: desolve(diff(y,x)+(y) == cos(x),y,show_method=True) [1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x), 'linear'] sage: desolve(diff(y,x)+(y) == cos(x),y,[0,1]) 1/2*(e^x*sin(x) + e^x*cos(x) + 1)*e^(-x) This ODE with separated variables is solved as exact. Explanation - factor does not split `e^{x-y}` in Maxima into `e^{x}e^{y}`:: sage: desolve(diff(y,x)==exp(x-y),y,show_method=True) [-e^x + e^y(x) == c, 'exact'] You can solve Bessel equations. You can also use initial conditions, but you cannot put (sometimes desired) initial condition at x=0, since this point is singlar point of the equation. Anyway, if the solution should be bounded at x=0, then k2=0.:: sage: desolve(x^2*diff(y,x,x)+x*diff(y,x)+(x^2-4)*y==0,y) k1*bessel_j(2, x) + k2*bessel_y(2, x) Difficult ODE produces error:: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Difficult ODE produces error - moreover, takes a long time :: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y,contrib_ode=True) # not tested Some more types od ODE's:: sage: desolve(x*diff(y,x)^2-(1+x*y)*diff(y,x)+y==0,y,contrib_ode=True,show_method=True) [[y(x) == c + log(x), y(x) == c*e^x], 'factor'] :: sage: desolve(diff(y,x)==(x+y)^2,y,contrib_ode=True,show_method=True) [[[x == c - arctan(sqrt(t)), y(x) == -x - sqrt(t)], [x == c + arctan(sqrt(t)), y(x) == -x + sqrt(t)]], 'lagrange'] These two examples produce error (as expected, Maxima 5.18 cannot solve equations from initial conditions). Current Maxima 5.18 returns false answer in this case!:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2]).expand() # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2],show_method=True) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Second order linear ODE:: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y) (k2*x + k1)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,show_method=True) [(k2*x + k1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1]) 1/2*(7*x + 6)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1],show_method=True) [1/2*(7*x + 6)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2]) 3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2],show_method=True) [3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y) (k2*x + k1)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,show_method=True) [(k2*x + k1)*e^(-x), 'constcoeff'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1]) (4*x + 3)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1],show_method=True) [(4*x + 3)*e^(-x), 'constcoeff'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2]) (2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2],show_method=True) [(2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x), 'constcoeff'] This equation can be solved within Maxima but not within Sage. It needs assumptions assume(x>0,y>0) and works in Maxima, but not in Sage:: sage: assume(x>0) # not tested sage: assume(y>0) # not tested sage: desolve(x*diff(y,x)-x*sqrt(y^2+x^2)-y,y,show_method=True) # not tested TESTS: Trac #6479 fixed:: sage: x = var('x') sage: y = function('y', x) sage: desolve( diff(y,x,x) == 0, y, [0,0,1]) x :: sage: desolve( diff(y,x,x) == 0, y, [0,1,1]) x + 1 AUTHORS: - David Joyner (1-2006) - Robert Bradshaw (10-2008) - Robert Marik (10-2009) """ if is_SymbolicEquation(de): de = de.lhs() - de.rhs() if is_SymbolicVariable(dvar): raise ValueError, "You have to declare dependent variable as a function, eg. y=function('y',x)" # for backwards compatibility if isinstance(dvar, list): dvar, ivar = dvar elif ivar is None: ivars = de.variables() ivars = [t for t in ivars if t is not dvar] if len(ivars) != 1: raise ValueError, "Unable to determine independent variable, please specify." ivar = ivars[0] def sanitize_var(exprs): return exprs.replace("'"+dvar_str+"("+ivar_str+")",dvar_str) dvar_str=dvar.operator()._maxima_().str() ivar_str=ivar._maxima_().str() de00 = de._maxima_().str() de0 = sanitize_var(de00) ode_solver="ode2" cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y(x),x) soln = maxima(cmd) if str(soln).strip() == 'false': if contrib_ode: ode_solver="contrib_ode" maxima("load('contrib_ode)") cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # (TEMP:contrib_ode(x*('diff(y,x,1))^2-(x*y+1)*'diff(y,x,1)+y,y,x), if TEMP=false then TEMP else substitute(y=y(x),TEMP)) soln = maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this ODE." else: raise NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." if show_method: maxima_method=maxima("method") if (ics is not None): if not is_SymbolicEquation(soln.sage()): raise NotImplementedError, "Maxima was unable to use initial condition for this equation (%s)"%(maxima_method.str()) if len(ics) == 2: tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() cmd="(TEMP:ic1(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=maxima(cmd) if len(ics) == 3: #fixed ic2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima maxima("ic2_sage(soln,xa,ya,dya):=block([programmode:true,backsubst:true,singsolve:true,temp,%k2,%k1,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(dya), boundtest('%k1,%k1), boundtest('%k2,%k2), \ temp: lhs(soln) - rhs(soln), \ TEMP_k:solve([subst([xa,ya],soln), subst([dya,xa], lhs(dya)=-subst(0,lhs(dya),diff(temp,lhs(xa)))/diff(temp,lhs(ya)))],[%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)), TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() tempic=tempic+",'diff("+dvar_str+","+ivar_str+")="+(ics[2])._maxima_().str() cmd="(TEMP:ic2_sage(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this IVP. Remove the initial contition to get the general solution." if len(ics) == 4: #fixed bc2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima maxima("bc2_sage(soln,xa,ya,xb,yb):=block([programmode:true,backsubst:true,singsolve:true,temp,%k1,%k2,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(xb), noteqn(yb), boundtest('%k1,%k1), boundtest('%k2,%k2), \ TEMP_k:solve([subst([xa,ya],soln), subst([xb,yb],soln)], [%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)),TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") cmd="bc2_sage(%s(%s,%s,%s),%s,%s=%s,%s,%s=%s)"%(ode_solver,de00,dvar_str,ivar_str,(ivar==ics[0])._maxima_().str(),dvar_str,(ics[1])._maxima_().str(),(ivar==ics[2])._maxima_().str(),dvar_str,(ics[3])._maxima_().str()) cmd="(TEMP:%s,substitute(%s=%s(%s),TEMP))"%(cmd,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:bc2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,x=%pi/2,y=2),substitute(y=y(x),TEMP)) soln=maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this BVP. Remove the initial contition to get the general solution." soln=soln.sage() if is_SymbolicEquation(soln) and soln.lhs() == dvar: # Remark: Here we do not check that the right hand side does not depend on dvar. # This probably will not hapen for soutions obtained via ode2, anyway. soln = soln.rhs() if show_method: return [soln,maxima_method.str()] else: return soln
def desolve(de, dvar, ics=None, ivar=None, show_method=False, contrib_ode=False): """ Solves a 1st or 2nd order linear ODE via maxima. Including IVP and BVP. *Use* ``desolve? <tab>`` *if the output in truncated in notebook.* INPUT: - ``de`` - an expression or equation representing the ODE - ``dvar`` - the dependent variable (hereafter called ``y``) - ``ics`` - (optional) the initial or boundary conditions - for a first-order equation, specify the initial ``x`` and ``y`` - for a second-order equation, specify the initial ``x``, ``y``, and ``dy/dx`` - for a second-order boundary solution, specify initial and final ``x`` and ``y`` initial conditions gives error if the solution is not SymbolisEquation (as happens for example for clairot equation) - ``ivar`` - (optional) the independent variable (hereafter called x), which must be specified if there is more than one independent variable in the equation. - ``show_method`` - (optional) if true, then Sage returns pair ``[solution, method]``, where method is the string describing method which has been used to get solution (Maxima uses the following order for first order equations: linear, separable, exact (including exact with integrating factor), homogeneous, bernoulli, generalized homogeneous) - use carefully in class, see below for the example of the equation which is separable but this property is not recognized by Maxima and equation is solved as exact. - ``contrib_ode`` - (optional) if true, desolve allows to solve clairot, lagrange, riccati and some other equations. May take a long time and thus turned off by default. Initial conditions can be used only if the result is one SymbolicEquation (does not contain singular solution, for example) OUTPUT: In most cases returns SymbolicEquation which defines the solution implicitly. If the result is in the form y(x)=... (happens for linear eqs.), returns the right-hand side only. The possible constant solutions of separable ODE's are omitted. EXAMPLES:: sage: x = var('x') sage: y = function('y', x) sage: desolve(diff(y,x) + y - 1, y) (c + e^x)*e^(-x) :: sage: f = desolve(diff(y,x) + y - 1, y, ics=[10,2]); f (e^10 + e^x)*e^(-x) :: sage: plot(f) We can also solve second-order differential equations.:: sage: x = var('x') sage: y = function('y', x) sage: de = diff(y,x,2) - y == x sage: desolve(de, y) k1*e^x + k2*e^(-x) - x :: sage: f = desolve(de, y, [10,2,1]); f -x + 5*e^(-x + 10) + 7*e^(x - 10) sage: f(x=10) 2 sage: diff(f,x)(x=10) 1 :: sage: de = diff(y,x,2) + y == 0 sage: desolve(de, y) k1*sin(x) + k2*cos(x) sage: desolve(de, y, [0,1,pi/2,4]) 4*sin(x) + cos(x) sage: desolve(y*diff(y,x)+sin(x)==0,y) -1/2*y(x)^2 == c - cos(x) Clairot equation: general and singular solutions:: sage: desolve(diff(y,x)^2+x*diff(y,x)-y==0,y,contrib_ode=True,show_method=True) [[y(x) == c^2 + c*x, y(x) == -1/4*x^2], 'clairault'] For equations involving more variables we specify independent variable:: sage: a,b,c,n=var('a b c n') sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True) [[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]] sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True,show_method=True) [[[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]], 'riccati'] Higher orded, not involving independent variable:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y).expand() 1/6*y(x)^3 + k1*y(x) == k2 + x sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3]).expand() 1/6*y(x)^3 - 5/3*y(x) == x - 3/2 sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3],show_method=True) [1/6*y(x)^3 - 5/3*y(x) == x - 3/2, 'freeofx'] Separable equations - Sage returns solution in implicit form:: sage: desolve(diff(y,x)*sin(y) == cos(x),y) -cos(y(x)) == c + sin(x) sage: desolve(diff(y,x)*sin(y) == cos(x),y,show_method=True) [-cos(y(x)) == c + sin(x), 'separable'] sage: desolve(diff(y,x)*sin(y) == cos(x),y,[pi/2,1]) -cos(y(x)) == sin(x) - cos(1) - 1 Linear equation - Sage returns the expression on the right hand side only:: sage: desolve(diff(y,x)+(y) == cos(x),y) 1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x) sage: desolve(diff(y,x)+(y) == cos(x),y,show_method=True) [1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x), 'linear'] sage: desolve(diff(y,x)+(y) == cos(x),y,[0,1]) 1/2*(e^x*sin(x) + e^x*cos(x) + 1)*e^(-x) This ODE with separated variables is solved as exact. Explanation - factor does not split `e^{x-y}` in Maxima into `e^{x}e^{y}`:: sage: desolve(diff(y,x)==exp(x-y),y,show_method=True) [-e^x + e^y(x) == c, 'exact'] You can solve Bessel equations. You can also use initial conditions, but you cannot put (sometimes desired) initial condition at x=0, since this point is singlar point of the equation. Anyway, if the solution should be bounded at x=0, then k2=0.:: sage: desolve(x^2*diff(y,x,x)+x*diff(y,x)+(x^2-4)*y==0,y) k1*bessel_j(2, x) + k2*bessel_y(2, x) Difficult ODE produces error:: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Difficult ODE produces error - moreover, takes a long time :: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y,contrib_ode=True) # not tested Some more types od ODE's:: sage: desolve(x*diff(y,x)^2-(1+x*y)*diff(y,x)+y==0,y,contrib_ode=True,show_method=True) [[y(x) == c + log(x), y(x) == c*e^x], 'factor'] :: sage: desolve(diff(y,x)==(x+y)^2,y,contrib_ode=True,show_method=True) [[[x == c - arctan(sqrt(t)), y(x) == -x - sqrt(t)], [x == c + arctan(sqrt(t)), y(x) == -x + sqrt(t)]], 'lagrange'] These two examples produce error (as expected, Maxima 5.18 cannot solve equations from initial conditions). Current Maxima 5.18 returns false answer in this case!:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2]).expand() # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2],show_method=True) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Second order linear ODE:: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y) (k2*x + k1)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,show_method=True) [(k2*x + k1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1]) 1/2*(7*x + 6)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1],show_method=True) [1/2*(7*x + 6)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2]) 3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2],show_method=True) [3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y) (k2*x + k1)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,show_method=True) [(k2*x + k1)*e^(-x), 'constcoeff'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1]) (4*x + 3)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1],show_method=True) [(4*x + 3)*e^(-x), 'constcoeff'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2]) (2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2],show_method=True) [(2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x), 'constcoeff'] This equation can be solved within Maxima but not within Sage. It needs assumptions assume(x>0,y>0) and works in Maxima, but not in Sage:: sage: assume(x>0) # not tested sage: assume(y>0) # not tested sage: desolve(x*diff(y,x)-x*sqrt(y^2+x^2)-y,y,show_method=True) # not tested TESTS: Trac #6479 fixed:: sage: x = var('x') sage: y = function('y', x) sage: desolve( diff(y,x,x) == 0, y, [0,0,1]) x :: sage: desolve( diff(y,x,x) == 0, y, [0,1,1]) x + 1 AUTHORS: - David Joyner (1-2006) - Robert Bradshaw (10-2008) - Robert Marik (10-2009) """ if is_SymbolicEquation(de): de = de.lhs() - de.rhs() if is_SymbolicVariable(dvar): raise ValueError, "You have to declare dependent variable as a function, eg. y=function('y',x)" # for backwards compatibility if isinstance(dvar, list): dvar, ivar = dvar elif ivar is None: ivars = de.variables() ivars = [t for t in ivars if t is not dvar] if len(ivars) != 1: raise ValueError, "Unable to determine independent variable, please specify." ivar = ivars[0] def sanitize_var(exprs): return exprs.replace("'"+dvar_str+"("+ivar_str+")",dvar_str) dvar_str=dvar.operator()._maxima_().str() ivar_str=ivar._maxima_().str() de00 = de._maxima_().str() de0 = sanitize_var(de00) ode_solver="ode2" cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y(x),x) soln = maxima(cmd) if str(soln).strip() == 'false': if contrib_ode: ode_solver="contrib_ode" maxima("load('contrib_ode)") cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # (TEMP:contrib_ode(x*('diff(y,x,1))^2-(x*y+1)*'diff(y,x,1)+y,y,x), if TEMP=false then TEMP else substitute(y=y(x),TEMP)) soln = maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this ODE." else: raise NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." if show_method: maxima_method=maxima("method") if (ics is not None): if not is_SymbolicEquation(soln.sage()): raise NotImplementedError, "Maxima was unable to use initial condition for this equation (%s)"%(maxima_method.str()) if len(ics) == 2: tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() cmd="(TEMP:ic1(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=maxima(cmd) if len(ics) == 3: #fixed ic2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima maxima("ic2_sage(soln,xa,ya,dya):=block([programmode:true,backsubst:true,singsolve:true,temp,%k2,%k1,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(dya), boundtest('%k1,%k1), boundtest('%k2,%k2), \ temp: lhs(soln) - rhs(soln), \ TEMP_k:solve([subst([xa,ya],soln), subst([dya,xa], lhs(dya)=-subst(0,lhs(dya),diff(temp,lhs(xa)))/diff(temp,lhs(ya)))],[%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)), TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() tempic=tempic+",'diff("+dvar_str+","+ivar_str+")="+(ics[2])._maxima_().str() cmd="(TEMP:ic2_sage(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this IVP. Remove the initial contition to get the general solution." if len(ics) == 4: #fixed bc2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima maxima("bc2_sage(soln,xa,ya,xb,yb):=block([programmode:true,backsubst:true,singsolve:true,temp,%k1,%k2,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(xb), noteqn(yb), boundtest('%k1,%k1), boundtest('%k2,%k2), \ TEMP_k:solve([subst([xa,ya],soln), subst([xb,yb],soln)], [%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)),TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") cmd="bc2_sage(%s(%s,%s,%s),%s,%s=%s,%s,%s=%s)"%(ode_solver,de00,dvar_str,ivar_str,(ivar==ics[0])._maxima_().str(),dvar_str,(ics[1])._maxima_().str(),(ivar==ics[2])._maxima_().str(),dvar_str,(ics[3])._maxima_().str()) cmd="(TEMP:%s,substitute(%s=%s(%s),TEMP))"%(cmd,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:bc2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,x=%pi/2,y=2),substitute(y=y(x),TEMP)) soln=maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this BVP. Remove the initial contition to get the general solution." soln=soln.sage() if is_SymbolicEquation(soln) and soln.lhs() == dvar: # Remark: Here we do not check that the right hand side does not depend on dvar. # This probably will not hapen for soutions obtained via ode2, anyway. soln = soln.rhs() if show_method: return [soln,maxima_method.str()] else: return soln
472,384
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
def desolve_system_strings(des,vars,ics=None): r""" Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) r""" d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
472,385
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: - ``de`` - a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") - ``vars`` - a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) - ``ics`` - a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
472,386
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES:: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
472,387
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: - David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
472,388
def eulers_method(f,x0,y0,h,x1,method="table"): """ This implements Euler's method for finding numerically the solution of the 1st order ODE ``y' = f(x,y)``, ``y(a)=c``. The "x" column of the table increments from ``x0`` to ``x1`` by ``h`` (so ``(x1-x0)/h`` must be an integer). In the "y" column, the new y-value equals the old y-value plus the corresponding entry in the last column. *For pedagogical purposes only.* EXAMPLES:: sage: from sage.calculus.desolvers import eulers_method sage: x,y = PolynomialRing(QQ,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1) x y h*f(x,y) 0 1 -2 1/2 -1 -7/4 1 -11/4 -11/8 :: sage: x,y = PolynomialRing(QQ,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1,method="none") [[0, 1], [1/2, -1], [1, -11/4], [3/2, -33/8]] :: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: x,y = PolynomialRing(RR,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1,method="None") [[0, 1], [1/2, -1.0], [1, -2.7], [3/2, -4.0]] :: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: x,y=PolynomialRing(RR,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1) x y h*f(x,y) 0 1 -2.0 1/2 -1.0 -1.7 1 -2.7 -1.3 :: sage: x,y=PolynomialRing(QQ,2,"xy").gens() sage: eulers_method(5*x+y-5,1,1,1/3,2) x y h*f(x,y) 1 1 1/3 4/3 4/3 1 5/3 7/3 17/9 2 38/9 83/27 :: sage: eulers_method(5*x+y-5,0,1,1/2,1,method="none") [[0, 1], [1/2, -1], [1, -11/4], [3/2, -33/8]] :: sage: pts = eulers_method(5*x+y-5,0,1,1/2,1,method="none") sage: P1 = list_plot(pts) sage: P2 = line(pts) sage: (P1+P2).show() AUTHORS: - David Joyner """ if method=="table": print "%10s %20s %25s"%("x","y","h*f(x,y)") n=int((1.0)*(x1-x0)/h) x00=x0; y00=y0 soln = [[x00,y00]] for i in range(n+1): if method=="table": print "%10r %20r %20r"%(x00,y00,h*f(x00,y00)) y00 = y00+h*f(x00,y00) x00=x00+h soln.append([x00,y00]) if method!="table": return soln
def eulers_method(f,x0,y0,h,x1,method="table"): r""" This implements Euler's method for finding numerically the solution of the 1st order ODE ``y' = f(x,y)``, ``y(a)=c``. The "x" column of the table increments from ``x0`` to ``x1`` by ``h`` (so ``(x1-x0)/h`` must be an integer). In the "y" column, the new y-value equals the old y-value plus the corresponding entry in the last column. *For pedagogical purposes only.* EXAMPLES:: sage: from sage.calculus.desolvers import eulers_method sage: x,y = PolynomialRing(QQ,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1) x y h*f(x,y) 0 1 -2 1/2 -1 -7/4 1 -11/4 -11/8 :: sage: x,y = PolynomialRing(QQ,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1,method="none") [[0, 1], [1/2, -1], [1, -11/4], [3/2, -33/8]] :: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: x,y = PolynomialRing(RR,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1,method="None") [[0, 1], [1/2, -1.0], [1, -2.7], [3/2, -4.0]] :: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: x,y=PolynomialRing(RR,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1) x y h*f(x,y) 0 1 -2.0 1/2 -1.0 -1.7 1 -2.7 -1.3 :: sage: x,y=PolynomialRing(QQ,2,"xy").gens() sage: eulers_method(5*x+y-5,1,1,1/3,2) x y h*f(x,y) 1 1 1/3 4/3 4/3 1 5/3 7/3 17/9 2 38/9 83/27 :: sage: eulers_method(5*x+y-5,0,1,1/2,1,method="none") [[0, 1], [1/2, -1], [1, -11/4], [3/2, -33/8]] :: sage: pts = eulers_method(5*x+y-5,0,1,1/2,1,method="none") sage: P1 = list_plot(pts) sage: P2 = line(pts) sage: (P1+P2).show() AUTHORS: - David Joyner r""" if method=="table": print "%10s %20s %25s"%("x","y","h*f(x,y)") n=int((1.0)*(x1-x0)/h) x00=x0; y00=y0 soln = [[x00,y00]] for i in range(n+1): if method=="table": print "%10r %20r %20r"%(x00,y00,h*f(x00,y00)) y00 = y00+h*f(x00,y00) x00=x00+h soln.append([x00,y00]) if method!="table": return soln
472,389
def eulers_method_2x2(f,g, t0, x0, y0, h, t1,method="table"): """ This implements Euler's method for finding numerically the solution of the 1st order system of two ODEs ``x' = f(t, x, y), x(t0)=x0.`` ``y' = g(t, x, y), y(t0)=y0.`` The "t" column of the table increments from `t_0` to `t_1` by `h` (so `\\frac{t_1-t_0}{h}` must be an integer). In the "x" column, the new x-value equals the old x-value plus the corresponding entry in the next (third) column. In the "y" column, the new y-value equals the old y-value plus the corresponding entry in the next (last) column. *For pedagogical purposes only.* EXAMPLES:: sage: from sage.calculus.desolvers import eulers_method_2x2 sage: t, x, y = PolynomialRing(QQ,3,"txy").gens() sage: f = x+y+t; g = x-y sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1,method="none") [[0, 0, 0], [1/3, 0, 0], [2/3, 1/9, 0], [1, 10/27, 1/27], [4/3, 68/81, 4/27]] :: sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 0 0 0 0 1/3 0 1/9 0 0 2/3 1/9 7/27 0 1/27 1 10/27 38/81 1/27 1/9 :: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: t,x,y=PolynomialRing(RR,3,"txy").gens() sage: f = x+y+t; g = x-y sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 0 0.00 0 0.00 1/3 0.00 0.13 0.00 0.00 2/3 0.13 0.29 0.00 0.043 1 0.41 0.57 0.043 0.15 To numerically approximate `y(1)`, where `(1+t^2)y''+y'-y=0`, `y(0)=1`, `y'(0)=-1`, using 4 steps of Euler's method, first convert to a system: `y_1' = y_2`, `y_1(0)=1`; `y_2' = \\frac{y_1-y_2}{1+t^2}`, `y_2(0)=-1`.:: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: t, x, y=PolynomialRing(RR,3,"txy").gens() sage: f = y; g = (x-y)/(1+t^2) sage: eulers_method_2x2(f,g, 0, 1, -1, 1/4, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 1 -0.25 -1 0.50 1/4 0.75 -0.12 -0.50 0.29 1/2 0.63 -0.054 -0.21 0.19 3/4 0.63 -0.0078 -0.031 0.11 1 0.63 0.020 0.079 0.071 To numerically approximate y(1), where `y''+ty'+y=0`, `y(0)=1`, `y'(0)=0`:: sage: t,x,y=PolynomialRing(RR,3,"txy").gens() sage: f = y; g = -x-y*t sage: eulers_method_2x2(f,g, 0, 1, 0, 1/4, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 1 0.00 0 -0.25 1/4 1.0 -0.062 -0.25 -0.23 1/2 0.94 -0.11 -0.46 -0.17 3/4 0.88 -0.15 -0.62 -0.10 1 0.75 -0.17 -0.68 -0.015 AUTHORS: - David Joyner """ if method=="table": print "%10s %20s %25s %20s %20s"%("t", "x","h*f(t,x,y)","y", "h*g(t,x,y)") n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): if method=="table": print "%10r %20r %25r %20r %20r"%(t00,x00,h*f(t00,x00,y00),y00,h*g(t00,x00,y00)) x01 = x00 + h*f(t00,x00,y00) y00 = y00 + h*g(t00,x00,y00) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) if method!="table": return soln
def eulers_method_2x2(f,g, t0, x0, y0, h, t1,method="table"): r""" This implements Euler's method for finding numerically the solution of the 1st order system of two ODEs ``x' = f(t, x, y), x(t0)=x0.`` ``y' = g(t, x, y), y(t0)=y0.`` The "t" column of the table increments from `t_0` to `t_1` by `h` (so `\\frac{t_1-t_0}{h}` must be an integer). In the "x" column, the new x-value equals the old x-value plus the corresponding entry in the next (third) column. In the "y" column, the new y-value equals the old y-value plus the corresponding entry in the next (last) column. *For pedagogical purposes only.* EXAMPLES:: sage: from sage.calculus.desolvers import eulers_method_2x2 sage: t, x, y = PolynomialRing(QQ,3,"txy").gens() sage: f = x+y+t; g = x-y sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1,method="none") [[0, 0, 0], [1/3, 0, 0], [2/3, 1/9, 0], [1, 10/27, 1/27], [4/3, 68/81, 4/27]] :: sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 0 0 0 0 1/3 0 1/9 0 0 2/3 1/9 7/27 0 1/27 1 10/27 38/81 1/27 1/9 :: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: t,x,y=PolynomialRing(RR,3,"txy").gens() sage: f = x+y+t; g = x-y sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 0 0.00 0 0.00 1/3 0.00 0.13 0.00 0.00 2/3 0.13 0.29 0.00 0.043 1 0.41 0.57 0.043 0.15 To numerically approximate `y(1)`, where `(1+t^2)y''+y'-y=0`, `y(0)=1`, `y'(0)=-1`, using 4 steps of Euler's method, first convert to a system: `y_1' = y_2`, `y_1(0)=1`; `y_2' = \\frac{y_1-y_2}{1+t^2}`, `y_2(0)=-1`.:: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: t, x, y=PolynomialRing(RR,3,"txy").gens() sage: f = y; g = (x-y)/(1+t^2) sage: eulers_method_2x2(f,g, 0, 1, -1, 1/4, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 1 -0.25 -1 0.50 1/4 0.75 -0.12 -0.50 0.29 1/2 0.63 -0.054 -0.21 0.19 3/4 0.63 -0.0078 -0.031 0.11 1 0.63 0.020 0.079 0.071 To numerically approximate y(1), where `y''+ty'+y=0`, `y(0)=1`, `y'(0)=0`:: sage: t,x,y=PolynomialRing(RR,3,"txy").gens() sage: f = y; g = -x-y*t sage: eulers_method_2x2(f,g, 0, 1, 0, 1/4, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 1 0.00 0 -0.25 1/4 1.0 -0.062 -0.25 -0.23 1/2 0.94 -0.11 -0.46 -0.17 3/4 0.88 -0.15 -0.62 -0.10 1 0.75 -0.17 -0.68 -0.015 AUTHORS: - David Joyner r""" if method=="table": print "%10s %20s %25s %20s %20s"%("t", "x","h*f(t,x,y)","y", "h*g(t,x,y)") n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): if method=="table": print "%10r %20r %25r %20r %20r"%(t00,x00,h*f(t00,x00,y00),y00,h*g(t00,x00,y00)) x01 = x00 + h*f(t00,x00,y00) y00 = y00 + h*g(t00,x00,y00) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) if method!="table": return soln
472,390
def eulers_method_2x2_plot(f,g, t0, x0, y0, h, t1): """ This plots the soln in the rectangle ``(xrange[0],xrange[1]) x (yrange[0],yrange[1])`` and plots using Euler's method the numerical solution of the 1st order ODEs `x' = f(t,x,y)`, `x(a)=x_0`, `y' = g(t,x,y)`, `y(a) = y_0`. *For pedagogical purposes only.* EXAMPLES:: The following example plots the solution to `\\theta''+\\sin(\\theta)=0`, `\\theta(0)=\\frac 34`, `\\theta'(0) = 0`. Type ``P[0].show()`` to plot the solution, ``(P[0]+P[1]).show()`` to plot `(t,\\theta(t))` and `(t,\\theta'(t))`:: sage: from sage.calculus.desolvers import eulers_method_2x2_plot sage: f = lambda z : z[2]; g = lambda z : -sin(z[1]) sage: P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0) """ n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): x01 = x00 + h*f([t00,x00,y00]) y00 = y00 + h*g([t00,x00,y00]) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) Q1 = line([[x[0],x[1]] for x in soln], rgbcolor=(1/4,1/8,3/4)) Q2 = line([[x[0],x[2]] for x in soln], rgbcolor=(1/2,1/8,1/4)) return [Q1,Q2]
def eulers_method_2x2_plot(f,g, t0, x0, y0, h, t1): r""" Plots solution of ODE This plots the soln in the rectangle ``(xrange[0],xrange[1]) x (yrange[0],yrange[1])`` and plots using Euler's method the numerical solution of the 1st order ODEs `x' = f(t,x,y)`, `x(a)=x_0`, `y' = g(t,x,y)`, `y(a) = y_0`. *For pedagogical purposes only.* EXAMPLES:: The following example plots the solution to `\\theta''+\\sin(\\theta)=0`, `\\theta(0)=\\frac 34`, `\\theta'(0) = 0`. Type ``P[0].show()`` to plot the solution, ``(P[0]+P[1]).show()`` to plot `(t,\\theta(t))` and `(t,\\theta'(t))`:: sage: from sage.calculus.desolvers import eulers_method_2x2_plot sage: f = lambda z : z[2]; g = lambda z : -sin(z[1]) sage: P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0) r""" Plots solution of ODE n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): x01 = x00 + h*f([t00,x00,y00]) y00 = y00 + h*g([t00,x00,y00]) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) Q1 = line([[x[0],x[1]] for x in soln], rgbcolor=(1/4,1/8,3/4)) Q2 = line([[x[0],x[2]] for x in soln], rgbcolor=(1/2,1/8,1/4)) return [Q1,Q2]
472,391
def eulers_method_2x2_plot(f,g, t0, x0, y0, h, t1): """ This plots the soln in the rectangle ``(xrange[0],xrange[1]) x (yrange[0],yrange[1])`` and plots using Euler's method the numerical solution of the 1st order ODEs `x' = f(t,x,y)`, `x(a)=x_0`, `y' = g(t,x,y)`, `y(a) = y_0`. *For pedagogical purposes only.* EXAMPLES:: The following example plots the solution to `\\theta''+\\sin(\\theta)=0`, `\\theta(0)=\\frac 34`, `\\theta'(0) = 0`. Type ``P[0].show()`` to plot the solution, ``(P[0]+P[1]).show()`` to plot `(t,\\theta(t))` and `(t,\\theta'(t))`:: sage: from sage.calculus.desolvers import eulers_method_2x2_plot sage: f = lambda z : z[2]; g = lambda z : -sin(z[1]) sage: P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0) """ n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): x01 = x00 + h*f([t00,x00,y00]) y00 = y00 + h*g([t00,x00,y00]) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) Q1 = line([[x[0],x[1]] for x in soln], rgbcolor=(1/4,1/8,3/4)) Q2 = line([[x[0],x[2]] for x in soln], rgbcolor=(1/2,1/8,1/4)) return [Q1,Q2]
def eulers_method_2x2_plot(f,g, t0, x0, y0, h, t1): """ This plots the soln in the rectangle ``(xrange[0],xrange[1]) x (yrange[0],yrange[1])`` and plots using Euler's method the numerical solution of the 1st order ODEs `x' = f(t,x,y)`, `x(a)=x_0`, `y' = g(t,x,y)`, `y(a) = y_0`. *For pedagogical purposes only.* EXAMPLES:: The following example plots the solution to `\theta''+\sin(\theta)=0`, `\theta(0)=\frac 34`, `\theta'(0) = 0`. Type ``P[0].show()`` to plot the solution, ``(P[0]+P[1]).show()`` to plot `(t,\\theta(t))` and `(t,\\theta'(t))`:: sage: from sage.calculus.desolvers import eulers_method_2x2_plot sage: f = lambda z : z[2]; g = lambda z : -sin(z[1]) sage: P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0) """ n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): x01 = x00 + h*f([t00,x00,y00]) y00 = y00 + h*g([t00,x00,y00]) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) Q1 = line([[x[0],x[1]] for x in soln], rgbcolor=(1/4,1/8,3/4)) Q2 = line([[x[0],x[2]] for x in soln], rgbcolor=(1/2,1/8,1/4)) return [Q1,Q2]
472,392
def eulers_method_2x2_plot(f,g, t0, x0, y0, h, t1): """ This plots the soln in the rectangle ``(xrange[0],xrange[1]) x (yrange[0],yrange[1])`` and plots using Euler's method the numerical solution of the 1st order ODEs `x' = f(t,x,y)`, `x(a)=x_0`, `y' = g(t,x,y)`, `y(a) = y_0`. *For pedagogical purposes only.* EXAMPLES:: The following example plots the solution to `\\theta''+\\sin(\\theta)=0`, `\\theta(0)=\\frac 34`, `\\theta'(0) = 0`. Type ``P[0].show()`` to plot the solution, ``(P[0]+P[1]).show()`` to plot `(t,\\theta(t))` and `(t,\\theta'(t))`:: sage: from sage.calculus.desolvers import eulers_method_2x2_plot sage: f = lambda z : z[2]; g = lambda z : -sin(z[1]) sage: P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0) """ n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): x01 = x00 + h*f([t00,x00,y00]) y00 = y00 + h*g([t00,x00,y00]) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) Q1 = line([[x[0],x[1]] for x in soln], rgbcolor=(1/4,1/8,3/4)) Q2 = line([[x[0],x[2]] for x in soln], rgbcolor=(1/2,1/8,1/4)) return [Q1,Q2]
def eulers_method_2x2_plot(f,g, t0, x0, y0, h, t1): """ This plots the soln in the rectangle ``(xrange[0],xrange[1]) x (yrange[0],yrange[1])`` and plots using Euler's method the numerical solution of the 1st order ODEs `x' = f(t,x,y)`, `x(a)=x_0`, `y' = g(t,x,y)`, `y(a) = y_0`. *For pedagogical purposes only.* EXAMPLES:: The following example plots the solution to `\\theta''+\\sin(\\theta)=0`, `\\theta(0)=\\frac 34`, `\\theta'(0) = 0`. Type ``P[0].show()`` to plot the solution, ``(P[0]+P[1]).show()`` to plot `(t,\theta(t))` and `(t,\theta'(t))`:: sage: f = lambda z : z[2]; g = lambda z : -sin(z[1]) sage: P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0) """ n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): x01 = x00 + h*f([t00,x00,y00]) y00 = y00 + h*g([t00,x00,y00]) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) Q1 = line([[x[0],x[1]] for x in soln], rgbcolor=(1/4,1/8,3/4)) Q2 = line([[x[0],x[2]] for x in soln], rgbcolor=(1/2,1/8,1/4)) return [Q1,Q2]
472,393
def _compute_faces(self): r""" Compute and cache faces of this polytope.
def _compute_faces(self): r""" Compute and cache faces of this polytope.
472,394
def faces(self, dim=None, codim=None): r""" Return the sequence of faces of this polytope.
def faces(self, dim=None, codim=None): r""" Return the sequence of faces of this polytope.
472,395
def points(self): r""" Return all lattice points of this polytope as columns of a matrix.
def points(self): r""" Return all lattice points of this polytope as columns of a matrix.
472,396
def integral(self, x=None, a=None, b=None, definite=False): r""" By default, returns the indefinite integral of the function. If definite=True is given, returns the definite integral.
def integral(self, x=None, a=None, b=None, definite=False): r""" By default, returns the indefinite integral of the function. If definite=True is given, returns the definite integral.
472,397
def change_weierstrass_model(self, *urst): r""" Return a new Weierstrass model of self under the standard transformation `(u,r,s,,t)`
def change_weierstrass_model(self, *urst): r""" Return a new Weierstrass model of self under the standard transformation `(u,r,s,,t)`
472,398
def change_weierstrass_model(self, *urst): r""" Return a new Weierstrass model of self under the standard transformation `(u,r,s,,t)`
def change_weierstrass_model(self, *urst): r""" Return a new Weierstrass model of self under the standard transformation `(u,r,s,,t)`
472,399