ASKSAGE: Sage Q&A Forum - Latest question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Tue, 10 Sep 2019 12:56:22 -0500Restriction of scalars for free moduleshttp://ask.sagemath.org/question/47823/restriction-of-scalars-for-free-modules/Suppose I have a free module `M` over `QQ[x]`. How do I obtain the underlying `QQ` vector space? FreeModule does not have this coercion:
<pre><code>sage: R = PolynomialRing(QQ,'x')
sage: R in CommutativeAlgebras(QQ)
True
sage: M = FreeModule(R,3)
sage: M in VectorSpaces(QQ)
False
</code></pre>
And `CombinatorialFreeModule` only takes already subcategories of `QQ`-vector spaces:
<pre><code>
sage: M = CombinatorialFreeModule(QQ, ['a','b','c'], category=Modules(R))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
....
ValueError: Subcategory of `Category of vector spaces with basis over Rational Field` required; got `Category of modules over Univariate Polynomial Ring in x over Rational Field`
</code></pre>heluaniTue, 10 Sep 2019 12:56:22 -0500http://ask.sagemath.org/question/47823/implement algebras with some extra structurehttp://ask.sagemath.org/question/47753/implement-algebras-with-some-extra-structure/I seem not to be understanding the way to implement categories with extra structure. Suppose I want to implement the category `Cs` of pairs `(A,S)` where `A` is a `QQ`-algebra and `S` is a linear endomorphism of `A` with the obvious morphisms. `Algebras(QQ)` is a full subcategory of `Cs` by adding the zero endormophism. And we also have the forgetful functor from `Cs` to `Algebras(QQ)` which consists to simply forget `S`.
Now from reading the examples in
https://doc.sagemath.org/html/en/reference/categories/index.html
or
https://doc.sagemath.org/html/en/thematic_tutorials/coercion_and_categories.html
I could set up
<pre><code>class Cs(Category)
def super_categories(self):
return[Algebras(QQ)]
</code></pre>
And that woul d give me a canonical forgetful functor `Cs` -> `Algebras(QQ)`. Now my problem is when I want to create a parent of `Cs()` starting from a parent in `Algebras(QQ)`. That is, I could set up a new parent and elements which will have to implement the methods for `Algebras(QQ)`:
<pre><code>sage: from sage.misc.abstract_method import abstract_methods_of_class
sage: abstract_methods_of_class(Algebras(QQ).parent_class)
{'optional': ['algebra_generators'], 'required': ['__contains__']}
sage: abstract_methods_of_class(Algebras(QQ).element_class)
{'optional': ['_add_', '_mul_'], 'required': ['__nonzero__']}
</code></pre>
But instead of implementing those methods I would want to use the methods of the underlying parent of `Algebras(QQ)`. Something like a hypothetical `PolynomialRing(QQ, 'x', category=Cs())`. In other words I'm looking to implement the functor `A -> (A, 0)` above.
Finally I have similar concerns about implementing `Cs()` in the other two possible ways, namely as the subcategory of the category of arrows in `VectorSpaces(QQ)` with the same source and target an object from `Algebras(QQ)`, or as a super category of `Algebras(QQ)` using `_subcategory_hook_`. Always I get to the point where I don't know how to implement something like `PolynomialRing(QQ, category=Cs())`. What I am doing now is keeping a copy of the algebra `A` inside of an instance of `Cs.parent_class` and then implementing the element and parent mehods of `Algebras(QQ)` by pointing to the corresponding methods of `A` but that seems silly. I'd appreciate any pointer.heluaniTue, 03 Sep 2019 14:05:43 -0500http://ask.sagemath.org/question/47753/Substituting symbolic expressions for mixed differential forms.http://ask.sagemath.org/question/47397/substituting-symbolic-expressions-for-mixed-differential-forms/I'm doing some computations with matrices differential forms, and the run times are extremely long. So in an attempt to
keep run times down, I'm attempting to do matrix computations with symbolic terms, and then later replacing them with the mixed forms I want.
However, there's the coercion from mixed forms into the symbolic ring, and this is presenting a problem for me.
As a toy example of what I'm trying to do, I have the set up (say)
Sage: p=1
Sage: q=2
Sage: M = Manifold((2*p*q), 'M', field='complex')
Sage: U = M.open_subset('U')
Sage: x = U.chart(names=tuple('x_%d' % i for i in range(2*p*q)))
Sage: eU = x.frame()
Sage: d = [M.diff_form(1) for i in range(q)]
Sage: for i in range(q):
Sage: d[i][i] = x[i]
Sage: D = [M.mixed_form(comp=([0, d[i], 0, 0, 0])) for i in range(q)]
Sage: c = {(i): var("c_{}".format(i)) for i in range(q)}
Sage: exp = 0
Sage: for i in range(q):
Sage: for j in range(q):
Sage: exp = exp + c[i]*c[j]
Now, in my actual project I will have many of these variables, so it's not feasible to manually type them into one substitution at once, so I need to do it with a for loop, so I try
Sage: for i in range(q):
Sage: exp.subs({c[i] : D[i]})
But this is where I get the coercion error.
As mentioned, the actual computations I'm dealing with involve large matrices of mixed forms, and the run times would be WAY shorter if I can do it all in symbolic matrices, and then transfer the expressions I get out (which come from taking a trace). How might I be able to achieve this? sum8tionMon, 05 Aug 2019 10:29:55 -0500http://ask.sagemath.org/question/47397/Is there a way to temporarily turn off sage's type checking?http://ask.sagemath.org/question/47227/is-there-a-way-to-temporarily-turn-off-sages-type-checking/ I'm having some difficulties writing sage code to solve linear programming problems using "natural variables", by substituting for them the variables required for MixedIntegerLinearProgram.
The code for "minimize_desired" is what I'd like to do, but it fails during the substitution with the error message "TypeError: no canonical coercion from Linear functions over Real Double Field to Symbolic Ring". What I'd like is for sage to just do the substitution and ignore the lack of coercion.
The code for "minimize_works" works, but I got past the type checking by changing everything to strings and then back into a sage object, which feels like a terrible kludge. However this does illustrate that, despite sage's worries about coercion, everything ends up fine for MixedIntegerLinearProgram.
Is there a way to turn off sage's type checking and just do the substitution?
Thanks,
Mike
Note: I simplified the examples below by eliminating all the code that dealt with constraints.
def minimize_desired(objective):
p = MixedIntegerLinearProgram(maximization=false)
pvar = p.new_variable(real=True, nonnegative=True)
variables=set(objective.arguments())
translation={v:pvar[v] for v in variables}
objective=objective.subs(translation) # FAILS HERE
p.set_objective(objective)
print p.solve()
def minimize_works(objective):
p = MixedIntegerLinearProgram(maximization=false)
pvar = p.new_variable(real=True, nonnegative=True)
variables=set(str(v) for v in objective.arguments())
translation={v:pvar[v] for v in variables}
objective=sageobj(str(objective), translation)
p.set_objective(objective)
print p.solve()
var('x y')
minimize_works(x+y)
print
minimize_desired(x+y)
millermjSat, 20 Jul 2019 19:24:18 -0500http://ask.sagemath.org/question/47227/Converting a symbolic expression to an element of a number fieldhttp://ask.sagemath.org/question/35184/converting-a-symbolic-expression-to-an-element-of-a-number-field/At some point in a calculation in the symbolic ring I end up with some numbers which are complex rationals of the form (a/b + I*(c/d). At this point I would like to no longer treat them as symbolic expressions and rather work with them in a more well behaved field. Since all of the computation I will be doing will keep things as complex rationals it seems like the number field `QQ[I]` is my best option.
**My question is**: How can I convert a symbolic expression like `SR(2/3+4/5*I)` to an element of `QQ[I]`. In general, there is no coercion from the symbolic ring to a number field, but in this special case there is a pretty clear map I would like to use.
Edit: I suppose since the map from the symbolic ring to the number field depends on an assumed embedding of the number field in the complex numbers, this might not be doable in any clean way. For now the following helper function works
<pre>
def SRtoQQI(v, imGen): # imGen = the immaginary unit in a ring QQ[I]
rp = QQ(v.real_part()) # get real part of input
ip = QQ(v.imag_part()) # get immaginary part of input
return rp + ip*imGen # combine parts to get output
</pre>
I am still interested to know if there is a build in way, maybe making use of the embedding maps from `QQ[I]` to `SR`.rlg23Tue, 18 Oct 2016 22:35:58 -0500http://ask.sagemath.org/question/35184/Coercion from PBW to universal enveloping algebrahttp://ask.sagemath.org/question/46483/coercion-from-pbw-to-universal-enveloping-algebra/I'm using *sage.algebras.lie_algebras.poincare_birkhoff_witt* to do computations in the universal enveloping algebras of some Lie algebras. I want to then use the resulting elements in the PBW basis to act on (a subalgebra) of the Lie algebra. For this I need to use the Lie algebra's bracket() method, which only works with elements of the Lie algebra.
Hence I need to coerce elements of PBW back into (NC polynomials of) elements of the Lie algebra. How do I do this?
Example
sage: lie_algebra = LieAlgebra(QQ, cartan_type='A4')
sage: pbw_basis = lie_algebra.pbw_basis()
sage: pbw_basis.an_element()
>>> PBW[alpha[4]]^2*PBW[alpha[3]]^2*PBW[alpha[2]]^3 + 2*PBW[alpha[4]] + 3*PBW[alpha[3]] + 1
Then I want to obtain
>>> E[alpha[4]]^2*E[alpha[3]]^2*E[alpha[2]]^3 + 2*E[alpha[4]] + 3*E[alpha[3]] + 1
Or rather it's enough if I can convert a term like PBW[alpha[4]] to E[alpha[4]], because I want to essentially use the following function
def universal_enveloping_algebra_action(pbw_elt,e):
result=0
for term,coefficient in pbw_elt:
sub_result=e
for factor,power in term:
for _ in range(power):
sub_result=lie_algebra.bracket(factor,sub_result)
result+=sub_result
return result
Here pbw_elt is an element of the PBW basis, and e is in the Lie algebra. In this case 'factor' needs to be coerced into an element of the Lie algebra.
Right now I solved the problem by making a dictionary converting algebra generators of pbw_basis into basis elements of the Lie algebra, but it feels like there should be a much more elegant solution.
TilpoFri, 10 May 2019 11:35:29 -0500http://ask.sagemath.org/question/46483/coercion between polynomial rings with block term ordershttp://ask.sagemath.org/question/45553/coercion-between-polynomial-rings-with-block-term-orders/ Hello,
I have the following problem:
I define a polynomial ring
R.<x,y> = PolynomialRing(QQ,2,order='deglex')
then I define a new polynomial ring, with an addition auxiliary variable and a polynomial in this ring
S = PolynomialRing(R.base(),['w1']+[str(v) for v in R.gens() ],order=TermOrder('lex',1)+R.term_order())
S.inject_variables(verbose=False)
f = w1*x^3 + w1*y + x^2 + y^2
then I define another polynomial ring, with another addition auxiliary variable. Coercing to this new ring works fine
T = PolynomialRing(S.base(),['w2']+[str(v) for v in S.gens() ],order=TermOrder('lex',1)+S.term_order())
f2 = T(f)
However the way backwards fails
S(f2)
> (...)
> /home/phil/Applications/SageMath/local/lib/python2.7/site-packages/sage/rings/polynomial/polynomial_ring.pyc in _coerce_map_from_(self, P)
791 from sage.rings.polynomial.multi_polynomial_ring import is_MPolynomialRing
792 if is_MPolynomialRing(P) and self.variable_name() in P.variable_names():
--> 793 P_ = P.remove_var(self.variable_name())
794 return self.base_ring()!=P_ and self.base_ring().has_coerce_map_from(P_)
795
> /home/phil/Applications/SageMath/local/lib/python2.7/site-packages/sage/rings/polynomial/multi_polynomial_ring_base.pyx in sage.rings.polynomial.multi_polynomial_ring_base.MPolynomialRing_base.remove_var (build/cythonized/sage/rings/polynomial/multi_polynomial_ring_base.c:5831)()
299 return PolynomialRing(self.base_ring(), vars, order=self.term_order())
300 except ValueError:
--> 301 raise ValueError("impossible to use the original term order (most likely because it was a block order). Please specify the term order for the subring")
302 else:
303 return PolynomialRing(self.base_ring(), vars, order=order)
> ValueError: impossible to use the original term order (most likely because it was a block order). Please specify the term order for the subring
Any ideas what I could do to prevent this problem? How would I specify the term order (as it was suggested)?
Kind regards,
PhilippPhilipp SchneiderTue, 26 Feb 2019 05:15:45 -0600http://ask.sagemath.org/question/45553/How to create a coercion on hyperbolic models?http://ask.sagemath.org/question/45228/how-to-create-a-coercion-on-hyperbolic-models/I want to put some text on my plots of the poincare disc model. I tried to do something like that,
word = text('my word',(real_part(P),imag_part(P)), color='black')
and gives me the following error,
TypeError: cannot coerce arguments: no canonical coercion from
Hyperbolic plane in the Poincare Disk Model to Symbolic Ring
Furthermore, this only works if my complex number P comes from the ring of complex numbers, not for a hyperbolic point. I need to configure some coercion. As substracting imaginary and real parts of a number in the poincare disk model. get_point method only work in one direction.
I am generating list of points like this.
Point in PD 0.150615998712507 - 0.101793686778004*I
and I want to add text in that coordinates, but I cannot find a way to coerce and get for example the complex number 0.1506 - 0.1017*I (even such exaggerate approximation will work in a plot)
Surely I am missing a method. Can you help me with this?
Thanks in advance
Gaston BurrullTue, 29 Jan 2019 05:46:03 -0600http://ask.sagemath.org/question/45228/codomain could not be determinedhttp://ask.sagemath.org/question/42732/codomain-could-not-be-determined/ I created an InfiniteDimensionalFreeAlgebra using CombinatorialFreeModule. It looks something like this:
class InfiniteDimensionalFreeAlgebra(CombinatorialFreeModule):
r""" The algebra generated by ``a[0], a[1], a[2], ...`` over the integers. """
def __init__(self,
base_ring=IntegerRing(),
prefix='a',
index_set=NonNegativeIntegerSemiring()):
self._base_ring = base_ring
self._basis_monoid = FreeMonoid(index_set=index_set, commutative=True, prefix=prefix)
# category
category = Algebras(self._base_ring.category()).WithBasis().Commutative()
category = category.or_subcategory(category)
# init
CombinatorialFreeModule.__init__(
self,
self._base_ring,
self._basis_monoid,
category=category,
prefix='',
bracket=False)
Now I want to view it as a *ring* and take symmetric polynomials over the ring. For example, in 2 variables, the following is one such symmetric polynomial:
2a[7] * x[1] + 2a[7] * x[2] + x[1]x[2] + 5
In my code, I attempt to initialize some Schur symmetric functions over this ring with something like:
a = InfiniteDimensionalFreeAlgebra()
sym = SymmetricFunctions(a)
s = sym.s()
one = s.one()
one_poly = one.expand(2)
at which point I run into the error `codomain could not be determined` when it attempts to apply some sort of morphism to the Schur function `one`. The full stacktrace is
Traceback (most recent call last):
File "./test_all.py", line 1162, in <module>
h = double_homogeneous(1, 1)
File "/Users/Matthew/programming/sage/morse-code/k_combinat_for_sage/all.py", line 664, in double_homogeneous
one_poly = one.expand(n)
File "/Users/Matthew/programming/sage/official-git-repo/local/lib/python2.7/site-packages/sage/combinat/sf/schur.py", line 537, in expand
return self._expand(condition, n, alphabet)
File "/Users/Matthew/programming/sage/official-git-repo/local/lib/python2.7/site-packages/sage/combinat/sf/sfa.py", line 4986, in _expand
return parent._apply_module_morphism(self, f)
File "/Users/Matthew/programming/sage/official-git-repo/local/lib/python2.7/site-packages/sage/categories/modules_with_basis.py", line 1096, in _apply_module_morphism
raise ValueError('codomain could not be determined')
ValueError: codomain could not be determined
and the full code can be found at [k_combinat_for_sage](https://github.com/MareoRaft/k_combinat_for_sage/blob/master/k_combinat_for_sage/all.py).
Thank you, your help is greatly appreciated.ml9nnMon, 25 Jun 2018 14:12:25 -0500http://ask.sagemath.org/question/42732/is it possible to coerce a tensor field module and FiniteRankFreeModule?http://ask.sagemath.org/question/42355/is-it-possible-to-coerce-a-tensor-field-module-and-finiterankfreemodule/M = Manifold(3, 'M')
U = M.open_subset('U')
V = M.open_subset('V')
M.declare_union(U,V);
c_xyz.<x,y,z> = U.chart()
c_uvw.<u,v,w> = V.chart()
eU = c_xyz.frame()
eV = c_uvw.frame()
T= M.tensor_field_module((1,1))
N = FiniteRankFreeModule(ZZ, 2, name='N')
T.coerce(N)
It is giving errorShouvikWed, 16 May 2018 12:10:35 -0500http://ask.sagemath.org/question/42355/coercion into/from subgroup or Tietze of generator changehttp://ask.sagemath.org/question/40483/coercion-intofrom-subgroup-or-tietze-of-generator-change/Hi there,
do you know of a function, which solves the Tietze for subgroups or converts elements from parentgroup to elements of subgroup and the other way round (if possible)?
Neither of the commented codes work (but I hope it is clear what I want):
F.<a,b,c> = FreeGroup()
x=a*b/c
H=F.subgroup([a*b,b,b*c])
y=H.gens()[1]*H.gens()[0]
x in H
y in F
#F(y)
#F.coerce(y)
#H.coerce(x).Tietze()
#H(x)
I am using cocalc, if this is a version thing.
I know something like that exists for quotient groups (s. http://doc.sagemath.org/html/en/reference/groups/sage/groups/finitely_presented.html )
In my use-case I have a free group $F$ and an element $x \in F$ in it.
Now I want for a given list of generators (e.g. in above [ a*b, b, b*c ]) the $x$ as a word of these generators,
hence I would like to see $x$ as an element in $H$ and use x.Tietze().
Another solution to my problem would be to swap the generators, but I can't see a way to do that either?ctstFri, 05 Jan 2018 17:53:14 -0600http://ask.sagemath.org/question/40483/Coerce an algebraic into a number field that contains ithttp://ask.sagemath.org/question/40020/coerce-an-algebraic-into-a-number-field-that-contains-it/ Consider the following code
r = QQbar.polynomial_root(x^5-x-1,CIF(RIF(0.1, 0.2), RIF(1.0, 1.1))
F,_,_ = number_field_elements_from_algebraics(r)
F(r)
Even though r can be coerced into an element of F, this coercion doesn't happen. What is the right thing for me to do? I'm interested in computing an algebraic number field that will contain a bunch of eigenvalues and want to express all the eigenvalues as elements of the number field. I've done the obvious workaround but the limitation expressed in the sample above isn't great.watson_laddFri, 08 Dec 2017 13:51:20 -0600http://ask.sagemath.org/question/40020/Multiplication of elements of tower fieldshttp://ask.sagemath.org/question/39835/multiplication-of-elements-of-tower-fields/Let
p=13
R = GF(p)
_.<v> = PolynomialRing(R)
R4.<v> = R.extension(v^4 - 2, 'v')
_.<w> = PolynomialRing(R4)
R16.<w> = R4.extension(w^4-v, 'w')
I need to compute
f1 = R16(1)
for i in range(34):
A=R4.random_element() #in my case, this is not random, its derived by an function
f1 = f1^2*A #this is not the whole code, but it displayes the problem
This element stays allways in R4. But the result i expect, is an element of R16.
So: How can I tell sage to use the R16 multiplication instead? I need a full degree 15 polynomial. If it is possible, in one variable (w, since w^4=v).
Furthermore: How can I tell Sage to print any coefficient in Hex?ShalecWed, 29 Nov 2017 02:31:10 -0600http://ask.sagemath.org/question/39835/Magma coercion equivalent in Sage?http://ask.sagemath.org/question/39521/magma-coercion-equivalent-in-sage/I'm working on converting a code written in Magma to Sage. I have something like this in Magma:
Fp;=FiniteField(p);
if (p mod 4) eq 3 then
q:=1;
else
q:=3;
while IsSquare(-Fp!q) do
q:=q+4;
end while;
end if;
Now there is the `!` operator used, which is called coercion in Magma. Is there an equivalent operator in Sage? I mean how would one conver the `IsSquare(-Fp!q)` part valid Sage?whateverMon, 13 Nov 2017 16:23:49 -0600http://ask.sagemath.org/question/39521/Why does simplify break print_latex_func?http://ask.sagemath.org/question/37328/why-does-simplify-break-print_latex_func/Here's a minimal example of what I am talking about. Both print statements should return the same output in this scenario.
,var n x
def my_latex_print(self, *args):
return "a_{%s}" %(', '.join(map(latex, args)))
a=function('a',nargs=1,print_latex_func=my_latex_print)(n)
sexp=a(n=n+1)+a(n=n)
print latex(sexp)
sexp=simplify(expand(sexp))
print latex(sexp)
However, the outputs differ:
a_{n + 1} + a_{n}
a\left(n + 1\right) + a\left(n\right)
Of course simplify-expand may lead to a different expression, but that's not what I am concerned about. I am concerned about the representation of `a(n)` instead of `a_n` in the output.
My main question is: How can I recover `a_n` out of `sexp` at the end of my code?BjörnTue, 18 Apr 2017 21:17:36 -0500http://ask.sagemath.org/question/37328/Coercion between quotients of $\mathbb{Z}$http://ask.sagemath.org/question/36264/coercion-between-quotients-of-mathbbz/Hello,
It is said [here](http://doc.sagemath.org/html/en/tutorial/tour_coercion.html#conversion-versus-coercion) that "in general there is no coercion between two different finite fields". When testing equality between elements of $\mathbb{Z}/(n)$ and $\mathbb{Z}/(m)$, why is there coercion to $\mathbb{Z}/(\gcd(m,n))$ only if $\gcd(m,n) \neq 1$ ?
zz3, zz5, zz6, zz10 = (ZZ.quotient(n) for n in [3,5,6,10])
zz6(0) == zz10(0) # True
zz3(0) == zz5(0) # False
I understand that testing equality in the null ring is not "useful", but why is it so inhomogeneous ? If some automated procedure depends on that feature, it would surely need to consider `zz3(0) == zz5(0)` to be true.tttupleThu, 12 Jan 2017 07:17:00 -0600http://ask.sagemath.org/question/36264/Coercion and Laurent polynomialhttp://ask.sagemath.org/question/33650/coercion-and-laurent-polynomial/
Hi! Is there a simple way to make easy coercion from Symbolic Ring to Laurent polynomial ring (or even algebraic extension)? I've only been able to bypass the problem by the following trick (and due the amount of time I've spent on this I'm happy to share it!) :
# Polynomial in the Symbolic Ring
var('t')
P = t^3 + 1/10*t + 3*t^-1
# Laurent polynomial
ringS.<t> = LaurentPolynomialRing(QQ)
#PP = ringS(P) # Not working
PP = ringS(sage_eval(str(P),locals={'t':t}))
print P, P.parent()
print PP, PP.parent()Arnaud1418Thu, 02 Jun 2016 13:11:36 -0500http://ask.sagemath.org/question/33650/Coercion on continued fractionshttp://ask.sagemath.org/question/33131/coercion-on-continued-fractions/Currently, when user types
sage: x = continued_fraction(pi)
sage: y = 3*x
an TypeError is raised saying
TypeError: unsupported operand parent(s) for '*': 'Integer Ring' and '<class 'sage.rings.continued_fraction.ContinuedFraction_real'>'
I understand that Sage tries to find common parent of Integer element and `ContinuedFraction_real` and fails. It seems that continued fractions in Sage are not implemented as elements of any particular field, and are derived directly from `SageObject`.
I am implementing an algorithm for arithmetical operations on continued fractions. Is it possible to make Sage call a particular method when the user tries to perform an arithmetical binary operation, where one of the operands is a continued fraction?
I have found those [1](http://doc.sagemath.org/html/en/reference/coercion/index.html#methods-to-implement), [2](http://doc.sagemath.org/html/en/reference/coercion/sage/structure/coerce.html), [3](http://doc.sagemath.org/html/en/tutorial/tour_coercion.html) links, but it seems that the topic of coercion is rather extensive and I don't know what to look for, as I don't know what the correct solution to the problem is.
Thank you for any response!mirgeeSun, 17 Apr 2016 07:49:52 -0500http://ask.sagemath.org/question/33131/Problem understanding coercions.http://ask.sagemath.org/question/32256/problem-understanding-coercions/Let :
sage: w = x^4 - (1+3*i)*x^3 - (2-4*i)*x^2 + (6-2*i)*x - 4 - 4*i
We can try to get its roots by (at least) two means :
1) Solution of a quartic :
sage: S1=[t.rhs() for t in solve(w,x)];S1
[-1/2*sqrt(2*I) + 3/2*I - 1/2, 1/2*sqrt(2*I) + 3/2*I - 1/2, -I + 1, I + 1]
sage: bool(sqrt(2*I)==1+I)
True
sage: S1R=[t.subs({sqrt(2*I):1+I}) for t in S1];S1R
[I - 1, 2*I, -I + 1, I + 1]
2) Roots of a polynom
sage: S2=[SR(t[0]) for t in w.roots(ring=QQbar)];S2
[-1 + 1*I, 2*I, 1 - 1*I, 1 + 1*I]
**I** am convinced tjat those two solutions are equal. But I fail to convince Sage :
sage: map(lambda t,u:t-u, S1R, S2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-be2e4183b522> in <module>()
----> 1 map(lambda t,u:t-u, S1R, S2)
<ipython-input-7-be2e4183b522> in <lambda>(t, u)
----> 1 map(lambda t,u:t-u, S1R, S2)
/usr/local/sage-7.0/src/sage/structure/element.pyx in sage.structure.element.RingElement.__sub__ (/usr/local/sage-7.0/src/build/cythonized/sage/structure/element.c:15995)()
1665 cdef long n
1666 if have_same_parent_c(left, right):
-> 1667 return (<ModuleElement>left)._sub_(<ModuleElement>right)
1668 if PyInt_CheckExact(right):
1669 n = PyInt_AS_LONG(right)
/usr/local/sage-7.0/src/sage/symbolic/expression.pyx in sage.symbolic.expression.Expression._sub_ (/usr/local/sage-7.0/src/build/cythonized/sage/symbolic/expression.cpp:20844)()
2950 relational_operator(_right._gobj))
2951 else:
-> 2952 x = gsub(left._gobj, _right._gobj)
2953 return new_Expression_from_GEx(left._parent, x)
2954
/usr/local/sage-7.0/src/sage/structure/element.pyx in sage.structure.element.RingElement.__add__ (/usr/local/sage-7.0/src/build/cythonized/sage/structure/element.c:15852)()
1649 elif PyInt_CheckExact(left):
1650 return (<RingElement>right)._add_long(PyInt_AS_LONG(left))
-> 1651 return coercion_model.bin_op(left, right, add)
1652
1653 cdef RingElement _add_long(self, long n):
/usr/local/sage-7.0/src/sage/structure/coerce.pyx in sage.structure.coerce.CoercionModel_cache_maps.bin_op (/usr/local/sage-7.0/src/build/cythonized/sage/structure/coerce.c:9736)()
1067 # We should really include the underlying error.
1068 # This causes so much headache.
-> 1069 raise TypeError(arith_error_message(x,y,op))
1070
1071 cpdef canonical_coercion(self, x, y):
TypeError: unsupported operand parent(s) for '+': 'Number Field in I with defining polynomial x^2 + 1' and 'Algebraic Field'
However, both lists are composed of some things seemongly belonging to SR :
sage: map(lambda t:type(t), S1R)
[<type 'sage.symbolic.expression.Expression'>,
<type 'sage.symbolic.expression.Expression'>,
<type 'sage.symbolic.expression.Expression'>,
<type 'sage.symbolic.expression.Expression'>]
sage: map(lambda t:type(t), S2)
[<type 'sage.symbolic.expression.Expression'>,
<type 'sage.symbolic.expression.Expression'>,
<type 'sage.symbolic.expression.Expression'>,
<type 'sage.symbolic.expression.Expression'>]
Worse, if I try to directly test for inequality, Sage **CRASHES** :
sage: S1R==S2
terminate called after throwing an instance of 'std::runtime_error'
what():
------------------------------------------------------------------------
/usr/local/sage-7.0/local/lib/python2.7/site-packages/sage/ext/interrupt/interrupt.so(+0x3c35)[0x7f53046bcc35]
/usr/local/sage-7.0/local/lib/python2.7/site-packages/sage/ext/interrupt/interrupt.so(+0x3c87)[0x7f53046bcc87]
/usr/local/sage-7.0/local/lib/python2.7/site-packages/sage/ext/interrupt/interrupt.so(+0x608c)[0x7f53046bf08c]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x10670)[0x7f530c439670]
/lib/x86_64-linux-gnu/libc.so.6(gsignal+0x37)[0x7f530b9ac657]
/lib/x86_64-linux-gnu/libc.so.6(abort+0x16a)[0x7f530b9ada2a]
/usr/lib/x86_64-linux-gnu/libstdc++.so.6(_ZN9__gnu_cxx27__verbose_terminate_handlerEv+0x15d)[0x7f52f803c35d]
/usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0x8d3b6)[0x7f52f803a3b6]
/usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0x8d401)[0x7f52f803a401]
/usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0x8d619)[0x7f52f803a619]
/usr/local/sage-7.0/local/lib/libpynac.so.2(_Z8py_errorPKc+0x49)[0x7f52dea919c9]
/usr/local/sage-7.0/local/lib/libpynac.so.2(_ZN5GiNaC7numericC1EP7_objectb+0x1b8)[0x7f52dea92508]
/usr/local/sage-7.0/local/lib/libpynac.so.2(_ZNK5GiNaC7numeric3addERKS0_+0x1c2)[0x7f52dea984f2]
/usr/local/sage-7.0/local/lib/libpynac.so.2(_ZN5GiNaCplERKNS_7numericES2_+0x9)[0x7f52dea9b569]
/usr/local/sage-7.0/local/lib/libpynac.so.2(_ZNK5GiNaC7numeric7add_dynERKS0_+0x2d)[0x7f52dea9305d]
/usr/local/sage-7.0/local/lib/libpynac.so.2(_ZN5GiNaC9expairseq21combine_overall_coeffERKNS_2exE+0x15)[0x7f52de9fe945]
/usr/local/sage-7.0/local/lib/libpynac.so.2(_ZN5GiNaC9expairseq19construct_from_2_exERKNS_2exES3_+0x27d)[0x7f52dea03bed]
/usr/local/sage-7.0/local/lib/libpynac.so.2(_ZN5GiNaC3addC1ERKNS_2exES3_+0x63)[0x7f52de9d5633]
/usr/local/sage-7.0/local/lib/libpynac.so.2(_ZN5GiNaCmiERKNS_2exES2_+0x5f)[0x7f52dea9c14f]
/usr/local/sage-7.0/local/lib/libpynac.so.2(_ZNK5GiNaC10relational6decideEv+0x3e)[0x7f52deaaaede]
/usr/local/sage-7.0/local/lib/python2.7/site-packages/sage/symbolic/expression.so(+0xa7108)[0x7f52de6c8108]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyObject_IsTrue+0x37)[0x7f530c6e4e17]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyObject_RichCompareBool+0x2c)[0x7f530c6e59cc]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(+0x8786c)[0x7f530c6cd86c]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyObject_RichCompare+0x72)[0x7f530c6e55d2]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x41b5)[0x7f530c74ba95]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x81c)[0x7f530c74e28c]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalCode+0x19)[0x7f530c74e3a9]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x5234)[0x7f530c74cb14]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x81c)[0x7f530c74e28c]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x5a42)[0x7f530c74d322]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x81c)[0x7f530c74e28c]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x5a42)[0x7f530c74d322]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x81c)[0x7f530c74e28c]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x5a42)[0x7f530c74d322]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x81c)[0x7f530c74e28c]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x5a42)[0x7f530c74d322]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x81c)[0x7f530c74e28c]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x5a42)[0x7f530c74d322]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x81c)[0x7f530c74e28c]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x5a42)[0x7f530c74d322]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x81c)[0x7f530c74e28c]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyEval_EvalCode+0x19)[0x7f530c74e3a9]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyRun_FileExFlags+0x8a)[0x7f530c771a9a]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(PyRun_SimpleFileExFlags+0xd7)[0x7f530c772e47]
/usr/local/sage-7.0/local/lib/libpython2.7.so.1.0(Py_Main+0xc3e)[0x7f530c7893ee]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f530b999870]
python(_start+0x29)[0x4006f9]
------------------------------------------------------------------------
Attaching gdb to process id 10517.
Saved trace to /home/charpent/.sage/crash_logs/sage_crash_w2E5Tn.log
------------------------------------------------------------------------
Unhandled SIGABRT: An abort() occurred in Sage.
This probably occurred because a *compiled* component of Sage has a bug
in it and is not properly wrapped with sig_on(), sig_off().
Sage will now terminate.
------------------------------------------------------------------------
Abandon
Hence two questions :
1. What in S2 is not convertible to SR and why ?
2. How should I test for equality ?
I'm a bit lost...
Emmanuel CharpentierSun, 17 Jan 2016 11:17:32 -0600http://ask.sagemath.org/question/32256/Converting polynomials between ringshttp://ask.sagemath.org/question/24207/converting-polynomials-between-rings/ I have two polynomials, each one explicitly created as members of different multivariate polynomial rings. So for example I might have
R1.<a,b,c,t> = PolynomialRing(QQ)
L = (a*t^2+b*t+c).subs(a=2,b=3,c=4)
R2.<A,B,C,D,t> = PolynomialRing(QQ)
p = (A*t+B)^2+(C*t+D)^2
Now I want to compare the coefficients of the two polynomials, which means converting L to be a polynomial in the ring R2.
However, I'm not sure (or more to the point, can't remember) how to do this. Is there some simple, canonical way to do this? Thanks!AlasdairFri, 19 Sep 2014 07:44:21 -0500http://ask.sagemath.org/question/24207/What are the different real numbers in Sage ?http://ask.sagemath.org/question/9950/what-are-the-different-real-numbers-in-sage/No computer can grasp the genuine real numbers, so I am trying to understand
how sage handles them (and going to write a small tutorial about this).
Here is a list of approaching objects i found:
#### Exact subfields of the reals: ####
- QQ = RationalField() The genuine
[rationals](http://www.sagemath.org/doc/reference/rings_standard/sage/rings/rational_field.html).
Denominators can be arbitrary big, the computations are exact, so the rounding
error is only made when approaching a real by a rational, not during furher computations. Notice that the size of the denominators may grow along the computations, which can therefore become very slow.
- NumberField? [number fields](http://www.sagemath.org/doc/reference/number_fields/sage/rings/number_field/number_field.html) described by an irreducible polynomial.
- AA = AlgebraicField() The genuine [algebraic numbers](http://www.sagemath.org/doc/reference/number_fields/sage/rings/qqbar.html). Computations are exact.
- SR = sage.symbolic.ring.SymbolicRing() This is the field made of expressions
like sqrt(2+pi). It handles a lot of real numbers but seems very slow.
Computations are not necessarily exact, since this field contains floating points
real numbers. Is there a way to express any algebraic number in SR ?
- CFF = ContinuedFractionField() reals are represented as a finite list of convergents. Claims it is exact but it actually approaches real numbers by rationals since the list of convergents are finite. However, we could imagine a future version using iterators instead of lists.
> sage: CFF(sqrt(2))^2
> [1, 1, 1491038293021224]
#### Floating point numbers: ####
- RDF = RealDoubleField() Those are the of [double precision floating numbers](http://www.sagemath.org/doc/reference/rings_numerical/sage/rings/real_double.html) the processor. Definitely the fastest, but a rounding is done at each computation.
- RR = RealField() Floating number with arbitrary (still fixed) many bits of
precision. [http://www.sagemath.org/doc/reference/rings_numerical/sage/rings/real_mpfr.html](http://www.sagemath.org/doc/reference/rings_numerical/sage/rings/real_mpfr.html)
Slower than RDF (in particular, atlas won't be used with them). Notice that
changing precision back and forth is a bad idea. Notice that NaN and Infinity belong to RDF and RR.
- RLF = RealLazyField() like RealField() but can wait that the user fixes the precision to get one. [http://www.sagemath.org/doc/reference/rings_numerical/sage/rings/real_lazy.html](http://www.sagemath.org/doc/reference/rings_numerical/sage/rings/real_lazy.html)
> sage: a = RLF(pi)
> sage: RealField(100)(a+2)
> 5.1415926535897932384626433833
- RIF = RealIntervalField() A real number is represented as an interval
containing it, and whose extremities are RealFields elements [http://www.sagemath.org/doc/reference/rings_numerical/sage/rings/real_mpfi.html](http://www.sagemath.org/doc/reference/rings_numerical/sage/rings/real_mpfi.html)
- RLF.interval_field() mixture of the two previous ones.
- sage.rings.real_lazy.LazyAlgebraic
#### Relations between those fields ####
- Two fields approaching the real numbers K and L can be compared using the
function composite_field(K,L), that finds the "best" field containing both K
and L.
> sage: composite_field(RDF,QQbar)
> Complex Double Field
- [Some](http://www.sagemath.org/doc/reference/number_fields/sage/rings/number_field/number_field_morphisms.html)
[maps](http://www.sagemath.org/doc/reference/number_fields/sage/rings/number_field/maps.html)
are also defined to embed an abstract number field into the real line.
- The method [algebraic_dependency()](http://www.sagemath.org/doc/reference/rings_numerical/sage/rings/real_double.html) that allows to guess whether a floating number corresponds to some algebraic number of a given degree.
Is this list complete or am i missing other real representations ? Im i wrong
in the previous descriptions ? Could you order them by speed, by number of
methods available (without coercion) ? Do you have any remark that could help
the beginner to understand the subtilities in the use of those fields in Sage ?
Given an algebraic number, is it faster to work on AA or on a number field (of
smaller dimension) containing it ? Notice that one can find such an associated
number field with the method [as_number_field_element()](http://www.sagemath.org/doc/reference/number_fields/sage/rings/qqbar.html#sage.rings.qqbar.AlgebraicNumber_base.as_number_field_element)
Do you have any hint, striking example, recommandations of use in special cases
that one should like to learn in a tutorial about real numbers ?
tmonteilThu, 28 Mar 2013 06:36:28 -0500http://ask.sagemath.org/question/9950/Matrices not equal, but entries are. Why?http://ask.sagemath.org/question/7516/matrices-not-equal-but-entries-are-why/Hi,
I've created a class which derives from RingElement and a class which derives from Ring, and made the latter the parent of the former. I have then placed the "elements" of this new ring I've constructed as entries into a matrix.
Given another such matrix with the same dimensions as the first, I have constructed its entries to be the same as the entries of the first matrix. The same means that when we compare entry (i,j) in the first matrix to entry (i,j) in the second, they are equal.
Why do the matrices not compare as equal? Is there anything you see in this error which could help me easily remedy this?
Here is the error I get:
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "_sage_input_58.py", line 10, in
> <module>
> exec compile(u'open("___code___.py","w").write("#
> -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("dnYgPSBtYXRyaXhfY2xlYW5lZF91cF9yZWR1Y3Rpb24oQV9BQikKQV9BQiA9PSBtYXRyaXhfY2xlYW5lZF91cF9yZWR1Y3Rpb24oQV9BQikuZ2V0X21hdHJpeF9BKCk="),globals())+"\\n");
> execfile(os.path.abspath("___code___.py"))
> File "", line 1, in <module>
> File "/tmp/tmplS8fJ8/___code___.py", line
> 3, in <module>
> exec compile(u'A_AB == matrix_cleaned_up_reduction(A_AB).get_matrix_A()
> File "", line 1, in <module>
> File "matrix_generic_dense.pyx", line 167,
> in
> sage.matrix.matrix_generic_dense.Matrix_generic_dense.__richcmp__
> (sage/matrix/matrix_generic_dense.c:3036)
> File "element.pyx", line 876, in
> sage.structure.element.Element._richcmp
> (sage/structure/element.c:8370) File
> "element.pyx", line 923, in
> sage.structure.element.Element._richcmp_c_impl
> (sage/structure/element.c:8671) File
> "matrix_dense.pyx", line 126, in
> sage.matrix.matrix_dense.Matrix_dense._cmp_c_impl
> (sage/matrix/matrix_dense.c:2757)
> File "element.pyx", line 913, in
> sage.structure.element.Element.__cmp__
> (sage/structure/element.c:8541) File
> "element.pyx", line 809, in
> sage.structure.element.Element._cmp
> (sage/structure/element.c:7239) File
> "coerce.pyx", line 880, in
> sage.structure.coerce.CoercionModel_cache_maps.canonical_coercion
> (sage/structure/coerce.c:8296) File
> "coerce.pyx", line 1419, in
> sage.structure.coerce.CoercionModel_cache_maps._coercion_error
> (sage/structure/coerce.c:14011)
> RuntimeError: There is a bug in the
> coercion code in Sage. Both x
> (=[((((1)(2)(3)(4), _, {{1}}, {{2},
> {1}}, {{2}, {3}, {1}}), {}), ())]) and
> y (=[((((1)(2)(3)(4), _, {{1}}, {{2},
> {1}}, {{2}, {3}, {1}}), {}), ())]) are
> supposed to have identical parents but
> they don't. In fact, x has parent
> 'Combinatorial Scalar Ring' whereas y
> has parent 'Combinatorial Scalar Ring'
> Original elements [((((1)(2)(3)(4), _,
> {{1}}, {{2}, {1}}, {{2}, {3}, {1}}),
> {}), ())] (parent Combinatorial Scalar
> Ring) and [((((1)(2)(3)(4), _, {{1}},
> {{2}, {1}}, {{2}, {3}, {1}}), {}),
> ())] (parent Combinatorial Scalar
> Ring) and maps <type 'NoneType'> None
> <type
> 'sage.structure.coerce_maps.DefaultConvertMap_unique'>
> Conversion map: From: Combinatorial
> Scalar Ring To: Combinatorial
> Scalar Ring
SLOtoSFThu, 15 Nov 2012 08:45:43 -0600http://ask.sagemath.org/question/7516/substitute algebraic numbers into a symbolic expressionhttp://ask.sagemath.org/question/9432/substitute-algebraic-numbers-into-a-symbolic-expression/How can I substitute algebraic numbers into a symbolic expression, in order to evaluate that expression with specific values for these variables? I tried the following:
var('a')
(a*3).substitute(a=AA(2))
but this yields
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "_sage_input_43.py", line 10, in <module>
exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("KGEqMykuc3Vic3RpdHV0ZShhPUFBKDEpKQ=="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
File "", line 1, in <module>
File "/private/var/folders/ft/9rycr1td4nxdkvbf122dg4rr0000gn/T/tmpaq8Q8E/___code___.py", line 3, in <module>
exec compile(u'(a*_sage_const_3 ).substitute(a=AA(_sage_const_1 ))
File "", line 1, in <module>
File "expression.pyx", line 3759, in sage.symbolic.expression.Expression.substitute (sage/symbolic/expression.cpp:18273)
File "expression.pyx", line 2304, in sage.symbolic.expression.Expression.coerce_in (sage/symbolic/expression.cpp:13187)
File "parent_old.pyx", line 234, in sage.structure.parent_old.Parent._coerce_ (sage/structure/parent_old.c:3573)
File "parent.pyx", line 1000, in sage.structure.parent.Parent.coerce (sage/structure/parent.c:8227)
TypeError: no canonical coercion from Algebraic Real Field to Symbolic Ring
How could I modify my code above to compute the result `6` using algebraic numbers along the way? In my real life scenario, I have several variables, so turning everything into polynomials in between doesn't feel right. On the other hand, all my coefficients in my expressions are integers, so there should be no problems due to inexact floating point numbers.MvGTue, 16 Oct 2012 01:43:20 -0500http://ask.sagemath.org/question/9432/coerce pari type or string to rational function workaround?http://ask.sagemath.org/question/8114/coerce-pari-type-or-string-to-rational-function-workaround/I am getting some rational functions from pari/gp and want to work with them in Sage. I can't figure out how to do the coercion. I tried coercing them directly, and even via a string.
Here's what I've tried:
Make a pari type rational function:
sage: test = gp.simplify((x+y)/y)
This is the field I want to put it in:
sage: R.<x,y> = PolynomialRing(QQ)
sage: S = R.fraction_field()
coercing directly doesn't work:
sage: S(test)
Traceback (most recent call last):
...
TypeError: unable to convert 1/y*x + 1 to a rational
So I tried making a string out of it:
sage: str(test)
'1/y*x + 1'
Of course, sage would accept that string if I typed it in directly:
sage: S(1/y*x + 1)
(x + y)/y
But it won't accept it as a string:
sage: S(str(test))
Traceback (most recent call last):
...
TypeError: no canonical coercion from Fraction Field of Multivariate Polynomial Ring in x, y over Rational Field to Rational Field
sage: S('1/y*x + 1')
Traceback (most recent call last):
...
TypeError: no canonical coercion from Fraction Field of Multivariate Polynomial Ring in x, y over Rational Field to Rational Field
All of this works fine for polynomials (just remove the denominator of y from the example above). I think these are bugs and I will report them as such, if you agree. But in the meantime, does anyone have a workaround I can use?Kate StangeSun, 22 May 2011 09:11:39 -0500http://ask.sagemath.org/question/8114/Cannot convert int to sage.rings.integer.Integerhttp://ask.sagemath.org/question/8099/cannot-convert-int-to-sageringsintegerinteger/I created a minimal example in the file bad.py
from sage.all import *
j = 0
m = matrix(3,3)
m.insert_row(j, [1,1,1])
Then from sage:
sage: load bad.py
TypeError: Cannot convert int to sage.rings.integer.Integer
I think I can see an easy workaround, I can wrap all the 1's in Integer() (or change the name of the file to .sage so the preparser does it), but why is that necessary? Is this a bug? Why would sage not be able to convert int to Integer? Isn't that a pretty obvious conversion?
paragonMon, 02 May 2011 07:23:12 -0500http://ask.sagemath.org/question/8099/Add a personnal coercion rulehttp://ask.sagemath.org/question/7892/add-a-personnal-coercion-rule/Hi all !
For some reasons I have to use a class MyAngle which basically describes an angle, but with some personal methods.
Obviously, sage's cos function cannot take an instance of my class as argument.
***SAGE***
#! /usr/bin/sage -python
# -*- coding: utf8 -*-
from sage.all import *
class MyAngle(object):
def __init__(self,value):
self.value=value
x=MyAngle(pi/2)
cos(x)
***ERROR***
Traceback (most recent call last):
File "./sagess.py", line 11, in <module>
cos(x)
File "function.pyx", line 733, in sage.symbolic.function.GinacFunction.__call__ (sage/symbolic/function.cpp:6572)
File "function.pyx", line 417, in sage.symbolic.function.Function.__call__ (sage/symbolic /function.cpp:4336)
TypeError: cannot coerce arguments: no canonical coercion from <class '__main__.MyAngle'> to Symbolic Ring
What do I have to add to my class to make Sage's cosine understand that when `x=MyAngle(pi/2)`,
cos(x)
means
cos(x.value)
I found that, but I didn't helped me so much.
http://www.sagemath.org/doc/developer/coding_in_python.html
Thanks for help !
have a good night
Laurent
Laurent ClaessensMon, 24 Jan 2011 05:53:09 -0600http://ask.sagemath.org/question/7892/Coercion problem while defining piecewise functionhttp://ask.sagemath.org/question/7895/coercion-problem-while-defining-piecewise-function/In a nutshell: I begin by defining the following function:
def g(x):
return math.exp(-1/(1 - x^2))
which poses no problem. Then, I try to use this function g to define a new function, as follows:
f = Piecewise([ [(-.5,.5), 0.44399*g(x)] ])
which returns the following error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Applications/sage/<ipython console> in <module>()
/Applications/sage/<ipython console> in g(x)
/Applications/sage/local/lib/python2.6/site-packages/sage/rings/fraction_field_element.so in sage.rings.fraction_field_element.FractionFieldElement.__float__ (sage/rings/fraction_field_element.c:8540)()
/Applications/sage/local/lib/python2.6/site-packages/sage/rings/polynomial/polynomial_element.so in sage.rings.polynomial.polynomial_element.Polynomial.__float__ (sage/rings/polynomial/polynomial_element.c:8243)()
TypeError: cannot coerce nonconstant polynomial to float
-----------
I am not sure of what is going wrong here. Any ideas/solutions would be deeply appreciated.
-jl
Jose LykonMon, 24 Jan 2011 18:52:38 -0600http://ask.sagemath.org/question/7895/