ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Thu, 22 Jul 2021 10:33:18 +0200TypeError: dist must be a Distribution instancehttps://ask.sagemath.org/question/58081/typeerror-dist-must-be-a-distribution-instance/Hi,
Suddenly, using Cython magic, I got the message **"TypeError: dist must be a Distribution instance"**.
I use Sage 9.3 Ubuntu with Jupyter and compile via %%cython -a.
I tried an other *ipynb* file, and there was no problem using Cython...<br>
Only one *ipynb* file seems to have this problem.
Further research shows that the probable cause is the use of **cython_lambda**.
Any solution is very appreciated.
RolandrolandThu, 22 Jul 2021 10:33:18 +0200https://ask.sagemath.org/question/58081/Why am I getting a type error when I attempt to take the projective closure of this intersection?https://ask.sagemath.org/question/56448/why-am-i-getting-a-type-error-when-i-attempt-to-take-the-projective-closure-of-this-intersection/I am attempting to take the projective closure of the intersection of the following affine polynomials (not the intersection of the closure!):
$$y^3-y-x^2= 0 $$
$$w^3-w+y^7-y^5-x^4y^3+x^4y = 0.$$
This affine intersection is a curve of dimension one. Unfortunately, I haven't been able to enter this lovely affine curve defined by this intersection into sage. When I attempt as follows:
A.<x,y,w> = AffineSpace(QQ, 3)
P.<u,v,t,s>=ProjectiveSpace(QQ,3)
C = Curve([y^3-y-x^2, w^3-w+y^7-y^5-x^4*y^3+x^4*y], A)
D=C.projective_closure(1,P)
I get an error at the definition of C due to the second polynomial:
TypeError: F (=[-x^4*y^3 + y^7 + x^4*y - y^5 + w^3 - w]) must be a list or tuple of polynomials of the coordinate ring of A (=Affine Space of dimension 3 over Finite Field of size 3)
I am so confused because this is absolutely in the coordinate ring of $A$. Why am I getting this type error? How can I enter this affine intersection into sage, so that I may take its closure?
_______________
As an aside, I can enter the intersection of the closure, which is not what I want, as follows:
x,y,z,w = GF(3)['x,y,z,w'].gens()
C = Curve([y^3-y*z^2-x^2*z, w^3*z^4-w*z^6+y^7-y^5*z^2-x^4*y^3+x^4*y*z^2]); C
The intersection of the closure has an extra irreducible component $[x: 0: w: 0]$,
masseygirlThu, 01 Apr 2021 05:08:59 +0200https://ask.sagemath.org/question/56448/The function run_doctests creates a TypeErrorhttps://ask.sagemath.org/question/56105/the-function-run_doctests-creates-a-typeerror/Hello everyone,
I've been writing a sage module in which I've written some documentation examples and tests. I wanted to run a doctest just to verify if everything is correct but function "run_doctests" seems to introduce a non-expected bug in the software. Here's an exampe:
sage: run_doctests("module.sage")
too few successful tests, not using stored timings
Running doctests with ID 2021-03-10-10-13-36-df8ccbc8.
Using --optional=sage
Doctesting 1 file.
sage -t /path-to-module.sage
[40 tests, 0.07 s]
----------------------------------------------------------------------
All tests passed!
----------------------------------------------------------------------
Total time for all tests: 0.1 seconds
cpu time: 0.1 seconds
cumulative wall time: 0.1 seconds
sage: M = ModularForms()
sage: M
Modular Forms space of dimension 0 for Modular Group SL(2,Z) of weight 2 over Rational Field
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/usr/lib/python3/dist-packages/sage/all_cmdline.py in <module>
----> 1 M
/usr/lib/python3/dist-packages/IPython/core/displayhook.py in __call__(self, result)
260 self.start_displayhook()
261 self.write_output_prompt()
--> 262 format_dict, md_dict = self.compute_format_data(result)
263 self.update_user_ns(result)
264 self.fill_exec_result(result)
/usr/lib/python3/dist-packages/IPython/core/displayhook.py in compute_format_data(self, result)
149
150 """
--> 151 return self.shell.display_formatter.format(result)
152
153 # This can be set to True by the write_output_prompt method in a subclass
/usr/lib/python3/dist-packages/sage/repl/display/formatter.py in format(self, obj, include, exclude)
198 """
199 # First, use Sage rich output if there is any
--> 200 sage_format, sage_metadata = self.dm.displayhook(obj)
201 assert PLAIN_TEXT in sage_format, 'plain text is always present'
202 if not set(sage_format.keys()).issubset(self.default_mime()):
TypeError: cannot unpack non-iterable NoneType object
Here's more info about the error: it happens whenever I use the run_doctests function. The run_doctests seems to work as it should. However, the problem occurs after I used this function. For example, If I define any object from any class (in my example ModularForms), then when use the special method _repr_ of that object I obtain this error message. I don't think this have anything to do with the ModularForms class.
Do anybody else know what could introduce this error? I was wondering if this error comes from my module or from Sagemath. In my module, I've been following the general conventions of the developper guide.
I've tried both SageMath version 9.0 (from the debian SID package) and SageMath version 9.3.beta8 (compiled from source) and I've got the same error with both versions. If this error comes from the software, I shall open a sage-trac ticket about this issue.
Thank you very much in advance!
edit: I added more information about the issue.DavidAyotteWed, 10 Mar 2021 16:42:35 +0100https://ask.sagemath.org/question/56105/find_root fails in for loop with type coercion errorhttps://ask.sagemath.org/question/55286/find_root-fails-in-for-loop-with-type-coercion-error/ Hi there, I'm trying to reproduce a model in the literature. Here is the code that causes the error (description+stack trace follows):
electron_chg = 1.6*10**(-19) # Coulombs
eps0 = 8.85418782e-12 # m^-3 kg^-1 s^4 A^2 = F/m
angs_per_meter = 1*10**10
T1 = 108
T11 = 120
T111 = 120
a10 = 3.34e5
a110 = 4.69e6
a1110 = -5.52e7
a12 = 3.23e8
a112 = 4.47e9
a123 = 4.91e9
m110 = -202e6
m1110 = 276e7
var('Px,Py,Pz, T')
a1(T) = a10*(T - T1)
a11(T) = a110*(T - T11)+m110
a111(T) = a1110*(T - T111)+m1110
Glan(Px,Py,Pz, T) = (a1(T))*(Px**2+Py**2+Pz**2) + (a11(T))*(Px**4+Py**4+Pz**4) + (a111(T))*(Px**6+Py**6+Pz**6) + a12*((Px**2)*(Py**2)+(Pz**2)*(Py**2)+(Px**2)*(Pz**2)) + a112*((Px**2)*(Py**4+Pz**4)+(Py**2)*(Px**4+Pz**4)+(Pz**2)*(Px**4+Py**4)) + a123*(Px**2)*(Py**2)*(Pz**2)
Ex(Px,Py,Pz, T) = derivative(Glan,Px)
Ey(Px,Py,Pz, T) = derivative(Glan,Py)
Ez(Px,Py,Pz, T) = derivative(Glan,Pz)
# this works
var('Ptet')
find_root(Ez(0,0,Ptet,32),0.0001,1.0)
# this doesn't, even for i = 0, which is the case that works above
var('Ptet')
Ptetx = zero_vector(101)
Ptety = zero_vector(101)
Ptetz = zero_vector(101)
for i in range(101):
print(i)
Ptetx[i] = find_root(Ex(0,0,Ptet,32+i),0.0001,1.0)
Ptety[i] = find_root(Ey(0,0,Ptet,32+i),0.0001,1.0)
Ptetz[i] = find_root(Ez(0,0,Ptet,32+i),0.0001,1.0)
Ptetx
Here is the full trace of the error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-3d8c5561fbc3> in <module>
5 for i in range(Integer(101)):
6 print(i)
----> 7 Ptetx[i] = find_root(Ex(Integer(0),Integer(0),Ptet,Integer(32)+i),RealNumber('0.0001'),RealNumber('1.0'))
8 Ptety[i] = find_root(Ey(Integer(0),Integer(0),Ptet,Integer(32)+i),RealNumber('0.0001'),RealNumber('1.0'))
9 Ptetz[i] = find_root(Ez(Integer(0),Integer(0),Ptet,Integer(32)+i),RealNumber('0.0001'),RealNumber('1.0'))
/opt/sagemath-9.2/local/lib/python3.7/site-packages/sage/modules/free_module_element.pyx in sage.modules.free_module_element.FreeModuleElement.__setitem__ (build/cythonized/sage/modules/free_module_element.c:13856)()
1813 if n < 0 or n >= d:
1814 raise IndexError("vector index out of range")
-> 1815 self.set_unsafe(n, R(value))
1816
1817 cdef int set_unsafe(self, Py_ssize_t i, value) except -1:
/opt/sagemath-9.2/local/lib/python3.7/site-packages/sage/structure/parent.pyx in sage.structure.parent.Parent.__call__ (build/cythonized/sage/structure/parent.c:9337)()
898 if mor is not None:
899 if no_extra_args:
--> 900 return mor._call_(x)
901 else:
902 return mor._call_with_args(x, args, kwds)
/opt/sagemath-9.2/local/lib/python3.7/site-packages/sage/structure/coerce_maps.pyx in sage.structure.coerce_maps.NamedConvertMap._call_ (build/cythonized/sage/structure/coerce_maps.c:6043)()
285 raise TypeError("Cannot coerce {} to {}".format(x, C))
286 cdef Map m
--> 287 cdef Element e = method(C)
288 if e is None:
289 raise RuntimeError("BUG in coercion model: {} method of {} returned None".format(self.method_name, type(x)))
/opt/sagemath-9.2/local/lib/python3.7/site-packages/sage/rings/real_mpfr.pyx in sage.rings.real_mpfr.RealNumber._integer_ (build/cythonized/sage/rings/real_mpfr.c:17319)()
2227 return n
2228
-> 2229 raise TypeError("Attempt to coerce non-integral RealNumber to Integer")
2230
2231 def integer_part(self):
TypeError: Attempt to coerce non-integral RealNumber to Integer
The error describes itself as a type coercion, but I can't see what the origin is, given that the 0 case works outside the loop. Could it be related to how range() works, is it different than the python implementation?akhhhhFri, 15 Jan 2021 17:54:16 +0100https://ask.sagemath.org/question/55286/nearby algebraic number / convert polynomial type to expression typehttps://ask.sagemath.org/question/52263/nearby-algebraic-number-convert-polynomial-type-to-expression-type/Given a real number, I am trying to find a nearby algebraic number. This can be done in Mathematica with the RootApproximant function.
I couldn't find a similar function in Sage, so I am using algdep() to find an irreducible polynomial that is approximately satisfied by that number. Then I am using roots() to find the roots of that polynomial, and I can identify which root is closest to my number.
The problem is that the output of algdep() has a type that seems to be incompatible with roots().
When I execute this code, p.roots() returns an empty list:
p=algdep(sqrt(5), 10);
print(p.roots())
When I execute this code, a list of the roots is returned:
q = x^2 - 5
print(q.roots())
The output of algdep() has type sage.rings.polynomial.polynomial_integer_dense_flint.Polynomial_integer_dense_flint
In the second block of code, q has type sage.symbolic.expression.Expression
Is there a way to convert the first type into the Expression type?
b897069Mon, 29 Jun 2020 23:17:05 +0200https://ask.sagemath.org/question/52263/Why is sage not recognizing symmetric polynomials as symmetric?https://ask.sagemath.org/question/50852/why-is-sage-not-recognizing-symmetric-polynomials-as-symmetric/ I am trying to decompose symmetric polynomials into polynomial combinations of elementary symmetric polynomials. It has been driving me absolutely up the wall, and I would be very grateful for any help.
It works perfectly with 2 variables.
S.<x0,x1>=QQ[]
f = (x0-x1)*(x1-x0)
Sym = SymmetricFunctions(QQ)
g = Sym.from_polynomial(f)
print g
For 3 variables it fails. Sage throws a type error and says the polynomial f is not symmetric, even though it is certainly invariant under the action of the symmetric group of order 3.
S.<x0,x1,x2>=QQ[]
f = (x0-x1)*(x1-x2)*(x2-x0)
Sym = SymmetricFunctions(QQ)
g = Sym.from_polynomial(f)
print g
The type error is as folliows:
/sage/combinat/sf/sf.pyc in from_polynomial(self, f)
1372 ValueError: x0 + 2*x1 + x2 is not a symmetric polynomial
1373 """
-> 1374 return self.m().from_polynomial(f)
1375
1376 def register_isomorphism(self, morphism, only_conversion=False):
However, the following does not throw a type error, perhaps because it is a linear combination of the elementary basis rather than a polynomial one. I don't understand what is going on. Why is this type error being triggered for a valid symmetric polynomial? Thank you very much for your time.
S.<x0,x1,x2>=QQ[]
f = (x0+x1)*(x1+x2)*(x2+x0)
Sym = SymmetricFunctions(QQ)
g = Sym.from_polynomial(f)
masseygirlSun, 19 Apr 2020 05:36:04 +0200https://ask.sagemath.org/question/50852/Why does solve() produces an error?https://ask.sagemath.org/question/49699/why-does-solve-produces-an-error/Why does solve() produces an error? `TypeError: The first argument must be a symbolic expression or a list of symbolic expressions.`
#!/usr/bin/env python
# coding: utf-8
# In[2]:
var('Ex Ey Ez')
# In[3]:
E=vector([Ex,Ey,Ez])
# In[4]:
var('Px Py Pz')
# In[5]:
P=vector([Px,Py,Pz])
# In[6]:
var('LAx LAy LAz LBx LBy LBz')
# In[7]:
LA=vector([LAx,LAy,LAz]); LB=vector([LBx,LBy,LBz])
# In[8]:
var('k QAx QAy')
# In[9]:
QA=QAx*LA+QAy*LB
# In[20]:
solve(E-P==k*(E-QA), [k, QAx, QAy])
# In[24]:
solve((E-P).cross_product(E-QA)==0, [QAx, QAy])portonTue, 28 Jan 2020 09:02:13 +0100https://ask.sagemath.org/question/49699/type error when using symbolic calculushttps://ask.sagemath.org/question/46423/type-error-when-using-symbolic-calculus/I have been using Sage for a few months. Up to now, plotting, polynomials, and arithmetic functions have been running fine.
Now I'm trying to use the symbolic calculation skills of Sage, but ...
I am getting the error : "unable to simplify to float approximation"
when running, for instance :
var('t')
sin(t)
on a locally hosted jupyter notebook running the SageMath 8.3 kernel. My OS is Ubuntu 18.04.
Same error in pure Sage :
sage: var('t')
t
sage: sin(t)
Traceback (most recent call last)
<ipython-input-3-17829414d33a> in <module>()
----> 1 sin(t)
/xxxxxxxxxxxxxxxxxxxxxx/lib/python2.7/site-packages/sage/symbolic/expression.pyx in
sage.symbolic.expression.Expression.__float__
(build/cythonized/sage/symbolic/expression.cpp:11836)()
1426 raise
1427 except TypeError:
-> 1428 raise TypeError("unable to simplify to float approximation")
1429 return ret
1430
TypeError: unable to simplify to float approximation
sage:gusThu, 02 May 2019 09:05:14 +0200https://ask.sagemath.org/question/46423/TypeError: cannot solve differential equationhttps://ask.sagemath.org/question/45730/typeerror-cannot-solve-differential-equation/I am trying to use sagemath to solve a system of ordinary differential equation. However, I failed and got an TypeError (This returns the following error: TypeError: Computation failed since Maxima requested additional constraints; using the 'assume' command before evaluation may help).
Here is my code for it. Could anyone help me with this? Thank you.
A=Matrix([[5/3, -4/3], [4/3, -5/3]])
B=Matrix([[2],[1]])
C=Matrix([-1,2])
D=Matrix([0])
t = var('t')
X=symb_mat(2,1,'X',t);
diffeqns = [eql == eqr \
for (eql,eqr) in zip(*[diff(X,t).list(),(A*X+B*u).list()])]
desolve_system(diffeqns,X.list(),ics=[0,1,2],ivar=t)jncn5565Sat, 09 Mar 2019 01:47:49 +0100https://ask.sagemath.org/question/45730/Compute xgcd over Gaussian integershttps://ask.sagemath.org/question/45441/compute-xgcd-over-gaussian-integers/As you can see below, I can create the ring of [Gaussian integers](https://en.wikipedia.org/wiki/Gaussian_integer) and compute the greatest common divisor of two elements:
sage: ZZ[I]
Gaussian Integers in Number Field in I with defining polynomial x^2 + 1
sage: F = ZZ[I].random_element()
sage: G = ZZ[I].random_element()
sage: F
-I - 4
sage: G
-I + 1
sage: gcd(F, G)
1
However, when I try to find $u, v \in \mathbf{Z}[i]$ such that $u\cdot F + v\cdot G = 1$ in $\mathbf{Z}[i]$ (that is, to run the extended GCD), I get the following error:
> sage: xgcd(F, G)
>. . .
> TypeError: Unable to coerce -I - 4 to an integer
Do you know how I can find such $u$ and $v$?Hilder Vitor Lima PereiraWed, 13 Feb 2019 10:25:35 +0100https://ask.sagemath.org/question/45441/TypeError 'unable to simplify to float approximation' while trying to define an integral operatorhttps://ask.sagemath.org/question/44805/typeerror-unable-to-simplify-to-float-approximation-while-trying-to-define-an-integral-operator/ Hello, I am trying to define an integral operator acting on a subspace of $L^2(\mathbb{R})$ that depends of time using sage. Being more explicit $W(t)$ takes a real function $f$ and returns another function $g$ defined by
\begin{equation}
W(t)f(x)=g(x)=\int_{-\infty}^{+\infty}K(x,y,z)f(y)\text{d}y
\end{equation}
This is the code I came up with
def W(t):
def dummy2(f):
def dummy3(x):
integrand(y)=f(y)*K(x,y,t)
return numerical_integral(integrand,-Infinity,+Infinity,algorithm='qag')[0]
return dummy3
return dummy2
With $K$ a reasonable function of $x,y,t$
However I am getting the following error
TypeError: unable to simplify to float approximation
I am pretty sure it's related to the types passed to numerical_integrand
What could be a solution? Or a better way to implement it?
Thank you allguesswhowhereSat, 29 Dec 2018 22:37:22 +0100https://ask.sagemath.org/question/44805/Variable Not Found while Plotting Finite Sumhttps://ask.sagemath.org/question/44530/variable-not-found-while-plotting-finite-sum/Today, while working on a discrete mathematics homework assignement, I came across this strange function:
$$ P(n) = \sum_{k=0}^{n}{\frac{(-1)^k (n-k)!}{k! \cdot n!}} $$.
Part of the question was to evaluate $\lim{n \rightarrow \infty}{P(n)}$ and as I had a hard time doing this by hand I gave it a shot with sagemath. I didn't expect it to evaluate the limit for me (which I tried and it didnt) but I was hoping to plot the graph in a straightforward manner. What I did is
```
var('k n')
```
,
```
p(n) = sum( (factorial(n-k)*(-1)^k)/factorial(k), k, 0, n)/factorial(n)
```
and finally
```
plot(p, (n, 1, 10))
```
which comes back with `ValueError: Variable 'k' not found`.
I found [this] (ask.sagemath.org/question/24293/plotting-value-error-variable-not-found/) related question which however seems to deal with an entirely different problem in the end. There is also [this] (groups.google.com/forum/#!topic/sage-support/azeRkbvtass) question which is closer to the problem I have, however the issue there seems to be that `p(4).n()` doesn't seem to work which happily provides an answer in my case. I have tried `plot(p(n).n(), (n, 1, 10))` which comes back as `TypeError: cannot evaluate symbolic expression numerically`. (Sorry for the non linked links, I will properly set them as soon as I have enough karma.)
I ended up working around the issue using `plot_list([p(i) for i in range(10)])` which was fine since I was interested mostly in integers anyway.
But why is this function not accepted using the normal `plot`? I also read somewhere that using matplotlib might be a workaround, however that'd introduce so much uneccessary syntax to my code. Also, if the issue here is that sagemath can't find a closed expression of my function, shouldn't there be a `plot_n` function that simply evaluates an argument numerically?HansZoellnerSat, 01 Dec 2018 18:30:52 +0100https://ask.sagemath.org/question/44530/Trouble finding intersection of two functionshttps://ask.sagemath.org/question/44019/trouble-finding-intersection-of-two-functions/ Hi all,
I'm still pretty new using SageMath, but I'm trying to duplicate functionality that I've been able to do in wolfram alpha
Wolfram Input:
Intersection points of [//math:90000 1.03^x//] and [//math:63000 1.095^x//]
So far I've been able to recreate and graph these functions very easily using SageMath, but I'm having a difficult time using the solve function to actually return a numerical value for the intersection point itself.
My SageMath code looks like:
x = var('x')
f1 = (63000*((1.095)^x))
f2 = (90000*((1.03)^x))
ans=solve(f2==f1,x)
print ans
print n(ans[0].rhs())
ans prints as
"[
219^x == 1/35*200^(x - 1)*103^x*100^(-x + 2)
]"
And I get an error "TypeError: cannot evaluate symbolic expression numerically" in my attempts to resolve it to an approximate number.
Can anyone tell me what I'm doing wrong?lgushurstMon, 22 Oct 2018 07:51:55 +0200https://ask.sagemath.org/question/44019/TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'sage.symbolic.expression.Expression'https://ask.sagemath.org/question/43196/typeerror-unsupported-operand-types-for-or-pow-list-and-sagesymbolicexpressionexpression/ When I enter following command in Sage Notebook;
var('x k w')
f = x^3 * e^(k*x) * sin(w*x)
show(f)
show(f.diff(x))
I get this error
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-e1add3252393> in <module>()
1 var('x k w')
----> 2 f = x**Integer(3) * e**(k*x) * sin(w*x)
3 show(f)
4 show(f.diff(x))
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'sage.symbolic.expression.Expression'
How can I resolve this issue.yasar11732Sun, 29 Jul 2018 15:17:42 +0200https://ask.sagemath.org/question/43196/TypeError : Object not iterablehttps://ask.sagemath.org/question/42769/typeerror-object-not-iterable/I am trying to build the multiplicative group of a finite field.
I define a finite field, its multiplicative group, and a conversion map
from the finite field to its multiplicative group as follows:
sage: F.<a> = GF(7^2)
sage: G = AbelianGroupWithValues([a], n=1,
....: gens_orders=[48], values_group=F)
sage: phi = G.convert_map_from(F)
Up to here, everything is fine.
Now there is an error when trying to use phi:
sage: phi(a)
Traceback (most recent call last)
...
TypeError: 'sage.rings.finite_rings.element_givaro.FiniteField_givaroElement' object is not iterable
What does this mean?mathjainThu, 28 Jun 2018 23:18:27 +0200https://ask.sagemath.org/question/42769/Multiplying matrices with different parentshttps://ask.sagemath.org/question/41642/multiplying-matrices-with-different-parents/ I am trying to multiple a symbolic 1x1 matrix with one element in it, by a square matrix over a finite field. for example
[-9*x0^2 - 11*x0*x1 - 5*x1^2 - 11*x0*x2 - 4*x1*x2 + 7*x2^2 + 13*x1*x3 + 8*x2*x3 + 4*x3^2 - 6*x0*x4 - 4*x1*x4 - 15*x2*x4 + 9*x0*x5 - 8*x1*x5 - 5*x2*x5 - 3*x3*x5]
to be multiplied with them matrix
[18 23 14 1 6 21]
[24 3 3 0 2 0]
[17 25 2 16 23 8]
[ 8 21 16 5 1 9]
[14 28 8 17 12 12]
[ 6 24 18 19 3 1]
however when i try this i get the following error:
TypeError: unsupported operand parent(s) for *: 'Full MatrixSpace of 1 by 1 dense matrices over Multivariate Polynomial Ring in x0, x1, x2, x3, x4, x5 over Finite Field of size 31' and 'Full MatrixSpace of 6 by 6 dense matrices over Finite Field of size 31'
Is there a way to do this? DalvirMon, 19 Mar 2018 19:00:57 +0100https://ask.sagemath.org/question/41642/Type error in matrix of differential formshttps://ask.sagemath.org/question/41230/type-error-in-matrix-of-differential-forms/I'm having problems tracing the exact problem in my code: I have matrices of differential forms and at some point I get type errors.
Consider the following example:
class Test:
def __init__(self):
self.z = var('z')
self.U = CoordinatePatch([self.z])
self.D = DifferentialForms(self.U)
self.d = self.D.gens()
self.M = Matrix(self.D,2)
print self.M
self.M[0,0] = self.d[0]
print self.M
print (self.M.base_ring() is self.D)
The first instance works without error, from the second onward I get a type error:
┌────────────────────────────────────────────────────────────────────┐
│ SageMath version 7.5.1, Release Date: 2017-01-15 │
│ Type "notebook()" for the browser-based notebook interface. │
│ Type "help()" for help. │
└────────────────────────────────────────────────────────────────────┘
sage: load('bugtest.sage')
sage: Test()
[0 0]
[0 0]
[dz 0]
[ 0 0]
True
<__main__.Test instance at 0x1edc7cbd8>
sage: Test()
[0 0]
[0 0]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-d1e5fd9e553c> in <module>()
----> 1 Test()
<string> in __init__(self)
/Applications/sage-7.5.1/src/sage/matrix/matrix0.pyx in sage.matrix.matrix0.Matrix.__repr__ (/Applications/sage-7.5.1/src/build/cythonized/sage/matrix/matrix0.c:11464)()
1664 """
1665 if self._nrows < max_rows and self._ncols < max_cols:
-> 1666 return self.str()
1667 if self.is_sparse():
1668 s = 'sparse'
/Applications/sage-7.5.1/src/sage/matrix/matrix0.pyx in sage.matrix.matrix0.Matrix.str (/Applications/sage-7.5.1/src/build/cythonized/sage/matrix/matrix0.c:13504)()
1876 rep = rep_mapping.get(x)
1877 else:
-> 1878 rep = repr(x)
1879 S.append(rep)
1880
/Applications/sage-7.5.1/src/sage/structure/sage_object.pyx in sage.structure.sage_object.SageObject.__repr__ (/Applications/sage-7.5.1/src/build/cythonized/sage/structure/sage_object.c:2691)()
190 return str(type(self))
191 else:
--> 192 result = repr_func()
193 if isinstance(result, unicode):
194 # Py3 compatibility: allow _repr_ to return unicode
/Applications/sage-7.5.1/local/lib/python2.7/site-packages/sage/tensor/differential_form_element.pyc in _repr_(self)
1006 format = DifferentialFormFormatter(self.parent().base_space())
1007 output = [format.repr(comp, fun) \
-> 1008 for (comp, fun) in self._components.items()]
1009 return ' + '.join(output)
1010
/Applications/sage-7.5.1/local/lib/python2.7/site-packages/sage/tensor/differential_form_element.pyc in repr(self, comp, fun)
161 [('d%r' % self._space.coordinate(c)) for c in comp])
162
--> 163 if fun == 1 and len(comp) > 0:
164 # We have a non-trivial form whose component function is 1,
165 # so we just return the formatted form part and ignore the 1.
/Applications/sage-7.5.1/src/sage/symbolic/expression.pyx in sage.symbolic.expression.Expression.__nonzero__ (/Applications/sage-7.5.1/src/build/cythonized/sage/symbolic/expression.cpp:17020)()
2574 return self.operator()(self.lhs().pyobject(), self.rhs().pyobject())
2575
-> 2576 pynac_result = decide_relational(self._gobj)
2577 if pynac_result == relational_undecidable:
2578 raise ValueError('undecidable relation: ' + repr(self))
/Applications/sage-7.5.1/src/sage/structure/element.pyx in sage.structure.element.Element.__add__ (/Applications/sage-7.5.1/src/build/cythonized/sage/structure/element.c:11198)()
1234 # Left and right are Sage elements => use coercion model
1235 if BOTH_ARE_ELEMENT(cl):
-> 1236 return coercion_model.bin_op(left, right, add)
1237
1238 try:
/Applications/sage-7.5.1/src/sage/structure/coerce.pyx in sage.structure.coerce.CoercionModel_cache_maps.bin_op (/Applications/sage-7.5.1/src/build/cythonized/sage/structure/coerce.c:10496)()
1105 # We should really include the underlying error.
1106 # This causes so much headache.
-> 1107 raise bin_op_exception(op, x, y)
1108
1109 cpdef canonical_coercion(self, x, y):
TypeError: unsupported operand parent(s) for '+': 'Algebra of differential forms in the variables z' and 'Integer Ring'
Maybe the symbolic variable is not "safe" inside a class?JonathanThu, 22 Feb 2018 10:07:48 +0100https://ask.sagemath.org/question/41230/How to create a Matrix with real numbers?https://ask.sagemath.org/question/37388/how-to-create-a-matrix-with-real-numbers/ I try to create a matrix with real number. When I try to create one, I get a TypeError message
Example:
sage: Z = matrix(2,2)
sage: Z[0,0] = sqrt(2)
--------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-29-94541bcbfa2b> in <module>()
----> 1 Z[Integer(0),Integer(0)] = sqrt(Integer(2))
sage/matrix/matrix0.pyx in sage.matrix.matrix0.Matrix.__setitem__ (/build/sagemath/src/sage-
7.6/src/src/build/cythonized/sage/matrix/matrix0.c:8316)()
sage/matrix/matrix0.pyx in sage.matrix.matrix0.Matrix._coerce_element (/build/sagemath/src/sage-
7.6/src/src/build/cythonized/sage/matrix/matrix0.c:9795)()
sage/structure/parent.pyx in sage.structure.parent.Parent.__call__ (/build/sagemath/src/sage-
7.6/src/src/build/cythonized/sage/structure/parent.c:9844)()
sage/structure/coerce_maps.pyx in sage.structure.coerce_maps.NamedConvertMap._call_
(/build/sagemath/src/sage-7.6/src/src/build/cythonized/sage/structure/coerce_maps.c:6402)()
sage/symbolic/expression.pyx in sage.symbolic.expression.Expression._integer_ (/build/sagemath/src/sage-
7.6/src/src/build/cythonized/sage/symbolic/expression.cpp:8607)()
TypeError: unable to convert sqrt(2) to an integer
Since I couldn't really find a way to create one in the documentation (at least I didn't find one), I would like to ask, if there is a easy solution to this.
Thank you very much
SelfesMon, 24 Apr 2017 16:30:12 +0200https://ask.sagemath.org/question/37388/Plotting point when coordinate involves symbolic and numerical valueshttps://ask.sagemath.org/question/34937/plotting-point-when-coordinate-involves-symbolic-and-numerical-values/Consider the following single piece of code:
point([real_part(zeta(I))+1,0])
When trying to compile it, I get the following error message:
Error in lines 1-1
Traceback (most recent call last):
File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 957, in execute
exec compile(block+'\n', '', 'single') in namespace, locals
File "", line 1, in <module>
File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/sage/plot/point.py", line 353, in point
return point3d(points, **kwds)
File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/sage/plot/plot3d/shapes2.py", line 1143, in point3d
A = sum([Point(z, size, **kwds) for z in v])
File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/sage/plot/plot3d/shapes2.py", line 720, in __init__
self.loc = (float(center[0]), float(center[1]), float(center[2]))
TypeError: 'sage.symbolic.expression.Expression' object does not support indexing
Is there some simple way to fix this?
Interesting note: I have played around with this error, and it is very unclear to me when it does or doesn't appear. Here are some examples of when the error *does* appear (as far as I've checked, the traceback is always the same):
point([real_part(zeta(I))+1,0])
point([real_part(zeta(I))*2,0])
point([real_part(zeta(I))+real_part(zeta(I)),0])
point([real_part(zeta(I))/2,0])
point([real_part(zeta(I))-real_part(zeta(2*I)),0])
Here are some examples where it *doesn't* appear:
point([real_part(zeta(I))+0,0])
point([real_part(zeta(I))*1,0])
point([real_part(zeta(I))*real_part(zeta(I)),0])
point([real_part(zeta(I))+real_part(zeta(2*I)),0])
point([real_part(zeta(I))+imag_part(zeta(I)),0])
(edit: the error doesn't seem to ever occur if we give the zeta function a real argument)
I'd be interested if someone figured out under what conditions the error appears or not, because I fail to see any pattern. Thank you in advance.WojowuSun, 25 Sep 2016 20:21:03 +0200https://ask.sagemath.org/question/34937/Errors when plotting zeta function parametricallyhttps://ask.sagemath.org/question/34882/errors-when-plotting-zeta-function-parametrically/ I have the following piece of code:
def f(x):
return(real_part(zeta(1+x*I)).n())
def g(x):
return(imag_part(zeta(1+x*I)).n())
parametric_plot([f(x),g(x)], (x,2,10))
It should be moderately clear what I'm trying to do - I want to produce a plot of Riemann zeta function on the line Re(z)=1 using parametric plotting. However, when I try to plot this, I get an error `TypeError: cannot evaluate symbolic expression numerically`. I also tried the same thing without the `.n()`, but then I get an error `TypeError: unable to coerce to a real number`. I couldn't find any help online.
It's worth noting that trying to plot function f(x) I get the same error with `.n()`, but it works just fine without it (as opposed to parametric plot). Does anyone have an idea how to fix the issue?
Thanks in advance.WojowuWed, 21 Sep 2016 16:46:11 +0200https://ask.sagemath.org/question/34882/Derivation of a sagemanifold vector (possible bug)https://ask.sagemath.org/question/33951/derivation-of-a-sagemanifold-vector-possible-bug/ I'm using sage v7.1 with sagemanifold v0.9 to calculate Lie derivatives.
<h2>The problem</h2>
I define my manifold, with a chart and the vectors which define the symmetry,
M = Manifold(4, 'M', latex_name=r"\mathcal{M}")
X.<t,r,th,ph> = M.chart(r't r:(0,+oo) th:(0,pi):\theta ph:(0,2*pi):\phi')
Lx = M.vector_field('Lx')
Lx[:] = [ 0, 0, -cos(ph), cot(th)*sin(ph) ]
Ly = M.vector_field('Ly')
Ly[:] = [ 0, 0, sin(ph), cot(th)*cos(ph) ]
Lz = M.vector_field('Lz')
Lz[:] = [ 0, 0, 0, 1]
Lt = M.vector_field('Lt')
Lt[:] = [ 1, 0, 0, 0]
However, if I call the derivative of a component of the vector like
diff( Lx[3], th )
I get a `TypeError`, because
type( Lx[3] )
<class 'sage.manifolds.coord_func_symb.CoordFunctionSymb'>
and it seems that the function `diff` only acts on SR expressions.
<h2>My bypass</h2>
Although I was able to bypass the situation, it would be nice if a solution was provided *out of the box*, but in case anyone else needs a solution:
I defined my vectors in a Sage way
xi0 = [ 1, 0, 0, 0]
xi1 = [ 0, 0, -cos(ph), cot(th)*sin(ph) ]
xi2 = [ 0, 0, sin(ph), cot(th)*cos(ph) ]
xi3 = [ 0, 0, 0, 1]
and then assigned them to the SageManifolds vector_field
Lx = M.vector_field('Lx')
Lx[:] = xi1
Ly = M.vector_field('Ly')
Ly[:] = xi2
Lz = M.vector_field('Lz')
Lz[:] = xi3
Lt = M.vector_field('Lt')
Lt[:] = xi0
So, when I need the derivative of a component of the vector, I calculate
diff(xi1[3], th)
Cheers.DoxTue, 28 Jun 2016 17:16:13 +0200https://ask.sagemath.org/question/33951/Integer not iterablehttps://ask.sagemath.org/question/32676/integer-not-iterable/ Not sure if this was asked before. I've been going through the Sage and Python tutorials for the past 3 weeks as I worked out that I'll eventually have to learn at least some Python so to get what I need from Sage. So far so good,
But this one escapes me. The Sage tutorial refers to this example in The Python library:
map(mul, [0, 1, 2, 3], [10, 20, 30, 40]) which is supposed to yield [0, 20, 60, 120]
However, I keep getting
...
...
TypeError: 'sage.rings.integer.Integer' object is not iterable
What's causing this?
Hope someone can help
Gerry
gerry_chuckSat, 27 Feb 2016 02:09:54 +0100https://ask.sagemath.org/question/32676/TypeError: unsupported operand for '*': integer and functionhttps://ask.sagemath.org/question/31911/typeerror-unsupported-operand-for-integer-and-function/To multiply an integer and a function seems to work in some cases:
f = lambda n: n
[2*f(n) for n in (0..9)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
On the other hand I often receive this error message but cannot see an
error in my code:
/projects/sage/sage-6.9/src/sage/structure/element.pyx in sage.structure.element.RingElement.__mul__ (/projects/sage/sage-6.9/src/build/cythonized/sage/structure/element.c:17265)()
1852 elif PyInt_CheckExact(left):
1853 return (<ModuleElement>right)._mul_long(PyInt_AS_LONG(left))
-> 1854 return coercion_model.bin_op(left, right, mul)
1855
1856 cpdef RingElement _mul_(self, RingElement right):
/projects/sage/sage-6.9/src/sage/structure/coerce.pyx in sage.structure.coerce.CoercionModel_cache_maps.bin_op (/projects/sage/sage-6.9/src/build/cythonized/sage/structure/coerce.c:9739)()
1068 # We should really include the underlying error.
1069 # This causes so much headache.
-> 1070 raise TypeError(arith_error_message(x,y,op))
1071
1072 cpdef canonical_coercion(self, x, y):
TypeError: unsupported operand parent(s) for '*': 'Integer Ring' and '<type 'function'>'
Can someone explain what is going wrong here?
**Edit:**
Now I see what is going wrong: my expectations lead me astray!
With Maple and f := n->n: two := n->2:
(1) seq(2*f(n), n=0..9);
(2) seq((2*f)(n), n=0..9);
(3) seq((two*f)(n), n=0..9);
*All* three versions lead to what I expect: 0, 2, 4, ...
Not so with SageMath! Here only (1) works, (2) and (3) give TypeErrors. I'd call Maple's approach more natural and user-friendly.
Perhaps things could be enhanced? The comment of the implementer "1069 # This causes so much headache" looks like this might be seen as a problem also by others.
Peter LuschnyTue, 29 Dec 2015 09:42:33 +0100https://ask.sagemath.org/question/31911/Cannot desolve ODEhttps://ask.sagemath.org/question/25632/cannot-desolve-ode/ I'm trying to compute the solution for a first order differential equation using the code below:
var('g, a, v_e, m_0, v_9, k')
m(t) = (m_0 - a*t)
v = function('v', t)
de = m*diff(v, t) == -v_e*diff(m, t) - k*v - m*g
ans = desolve(de, v, ics=[0,0], ivar=t)
This returns the following error:
TypeError: Computation failed since Maxima requested additional constraints; using the 'assume' command before evaluation *may* help (example of legal syntax is 'assume(-k/a>0)', see `assume?` for more details)
Running assume(-k/a>0) before desolve does not remove the error. This error does not happen with the k*v term removed. By hand, I was able to solve this DE using integrating factors.
lscottThu, 29 Jan 2015 00:03:45 +0100https://ask.sagemath.org/question/25632/density_plot + def'ed python function = TypeError?https://ask.sagemath.org/question/25617/density_plot-defed-python-function-typeerror/I have the following functions:
var('a, b')
# This will work with both contour_plot and density_plot
f1(a, b) = 1 - b / a
# So will this
f2(a, b) = 1 - a / b
# This only works with contour_plot?!
def f12(a, b):
if a - b < 0:
return f1(a, b)
else:
return f2(a, b)
Obviously, `f1` and `f2` are symbolic functions, where `f12` is a `def`'ed python function. Calling `contour_plot` works on all three. Calling `density_plot` works on `f1` and `f2`, but raises a `TypeError` when called with `f12`, the `def`'ed python function.
I've [created a project](https://cloud.sagemath.com/projects/443a2a33-d145-4b63-893f-175543cc50c6/files/Test%20Case.sagews) that has an interactive session demonstrating the problem.
Here's the trace:
Error in lines 1-1
Traceback (most recent call last):
...
File "/projects/443a2a33-d145-4b63-893f-175543cc50c6/.sagemathcloud/sage_salvus.py", line 2306, in show
show_2d_plot_using_matplotlib(obj, svg=svg, **kwds)
File "/projects/443a2a33-d145-4b63-893f-175543cc50c6/.sagemathcloud/sage_salvus.py", line 2229, in show_2d_plot_using_matplotlib
obj.save(t, **kwds)
File "/usr/local/sage/sage-6.4/local/lib/python2.7/site-packages/sage/misc/decorators.py", line 471, in wrapper
return func(*args, **kwds)
File "/usr/local/sage/sage-6.4/local/lib/python2.7/site-packages/sage/plot/graphics.py", line 2972, in save
figure = self.matplotlib(**options)
File "/usr/local/sage/sage-6.4/local/lib/python2.7/site-packages/sage/plot/graphics.py", line 2418, in matplotlib
g._render_on_subplot(subplot)
File "/usr/local/sage/sage-6.4/local/lib/python2.7/site-packages/sage/plot/density_plot.py", line 146, in _render_on_subplot
subplot.imshow(self.xy_data_array, origin='lower', cmap=cmap, extent=(x0,x1,y0,y1), interpolation=options['interpolation'])
File "/usr/local/sage/sage-6.4/local/lib/python2.7/site-packages/matplotlib-1.3.1-py2.7-linux-x86_64.egg/matplotlib/axes.py", line 7300, in imshow
im.set_data(X)
File "/usr/local/sage/sage-6.4/local/lib/python2.7/site-packages/matplotlib-1.3.1-py2.7-linux-x86_64.egg/matplotlib/image.py", line 425, in set_data
raise TypeError("Image data can not convert to float")
TypeError: Image data can not convert to float
Am I asking `density_plot` to do something crazy here? If not, what am I doing wrong?positaTue, 27 Jan 2015 20:32:24 +0100https://ask.sagemath.org/question/25617/Error plotting root systems in Sagehttps://ask.sagemath.org/question/25415/error-plotting-root-systems-in-sage/ I am trying to use the Sage package for root systems, but it keeps returning an error. Here is what I am trying to do in the Notebook of Sage 5.7: I enter exactly the following lines from the tutorial for visualizing root systems
sage: L = RootSystem(["A",2]).ambient_space()
sage: L.plot()
The output I get is a traceback ending in 'unsupported operand parent(s) for '*': Full matrix Space of 2 by 2 dense matrices over real field with 53 bits of precision and vector space of dimension 3 over rational field'
I do not understand what I am doing wrong and what this message means. I am a newcomer to sage and all I want is to print a root system with some weights added for illustration purposes. I would appreciate any pointers.guestTue, 06 Jan 2015 22:45:41 +0100https://ask.sagemath.org/question/25415/Strange type error in interactivehttps://ask.sagemath.org/question/10662/strange-type-error-in-interactive/I'm trying to make a simple interactive for my students to practice differentiating polynomials. For some reason, when an answer is entered, Sage tries to convert it (a polynomial) to an instance of sage.structure.parent.Parent and chokes. The same code run outside of an interactive works fine. Why is Sage trying to do this conversion and how do I get it to stop?
#Create polynomial generator
poly.<x>=PolynomialRing(QQ)
#Problems correct (in a row and total)
streak = 0
tot = 0
first = True
@interact
def polyDiff(ans=input_box(label="f'(x)=", type=sage.rings.polynomial.polynomial_rational_flint.Polynomial_rational_flint)):
#Load persistent variables
global streak
global tot
global first
global poly
#Set up and display problem on first run
if (first == True):
rand_poly=poly.random_element(2)
first = False
html("f(x)=")+html(rand_poly)
#Define correct answer
corr = diff(rand_poly, x)
#Check student's answer
if (ans is not None):
if (corr == ans):
print "Correct!"
tot += 1
streak += 1
#Generate new problem
rand_poly = poly.random_element(5)
else:
html("Try again")
streak = 0
else:
print "Enter your answer"
jaiaSun, 27 Oct 2013 00:18:17 +0200https://ask.sagemath.org/question/10662/TypeError: ECL says: Maxima asks: Is y positive, negative, or zero?https://ask.sagemath.org/question/10636/typeerror-ecl-says-maxima-asks-is-y-positive-negative-or-zero/I'm using sage to give me the inverse of functions using solve(). Most of the time, it works fine. But when I have roots of anything involved(for example, "solve((5x-2)^(1/7)==y,x)", I get the error message in the title. Is there any way around this?SnapSun, 20 Oct 2013 10:22:35 +0200https://ask.sagemath.org/question/10636/TypeError: FIXNUM.https://ask.sagemath.org/question/10058/typeerror-fixnum/Hi everyone,
I am using function taylor() in sage to find the Taylor series of a function as follows:
var ('x')
fx = e^(-(1/632936348449528153)*(x))
taylor(fx,x,1,2)
it gives me the correct answer. But when the the denominator in the exponent (i.e. the denominator of 1/632936348449528153) is increased further by one digit (say 9) I receive the following error message
TypeError: ECL says: 6329363484495281539 is not of type FIXNUM.
My actual function is like
a=e^(-(1/632936348449528153937412733512609636)*(x1))
But when I use the above function again in taylor(), I get the error as shown below.
TypeError: ECL says: 632936348449528153937412733512609636 is not of type FIXNUM.
Is there any solution to overcome this error????
Note: I am using sage in the Sage Notebook online in a browser.
assadabbasiTue, 23 Apr 2013 23:31:26 +0200https://ask.sagemath.org/question/10058/backslash operator on RDF matriceshttps://ask.sagemath.org/question/9787/backslash-operator-on-rdf-matrices/I've discovered that the backslash operator produces a weird type error when used on matrices with Real Double Field entries:
----------------------------------------------------------------------
| Sage Version 5.6, Release Date: 2013-01-21 |
| Type "notebook()" for the browser-based notebook interface. |
| Type "help()" for help. |
----------------------------------------------------------------------
sage: A = matrix(QQ, 3, [1,2,4,2,3,1,0,1,2])
sage: B = matrix(QQ, 3, 2, [1,7,5,2,1,3])
sage: A\B
[ -1 1]
[13/5 -3/5]
[-4/5 9/5]
sage: A = matrix(RDF, 3, [1,2,4,2,3,1,0,1,2])
sage: B = matrix(RDF, 3, 2, [1,7,5,2,1,3])
sage: A\B
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/gtmarks/<ipython console> in <module>()
/usr/local/sage-5.6/local/lib/python2.7/site-packages/sage/misc/preparser.pyc in __mul__(self, right)
1398 (0.0, 0.5, 1.0, 1.5, 2.0)
1399 """
-> 1400 return self.left._backslash_(right)
1401
1402
/usr/local/sage-5.6/local/lib/python2.7/site-packages/sage/matrix/matrix2.so in sage.matrix.matrix2.Matrix._backslash_ (sage/matrix/matrix2.c:3658)()
/usr/local/sage-5.6/local/lib/python2.7/site-packages/sage/matrix/matrix_double_dense.so in sage.matrix.matrix_double_dense.Matrix_double_dense.solve_right (sage/matrix/matrix_double_dense.c:11636)()
TypeError: vector of constants over Real Double Field incompatible with matrix over Real Double Field
I don't understand the final "imcompatibility" message: both the vector and the matrix are RDF type, so how could they be incompatible? This is a small version of a problem I encountered in the context of an attempt to demonstrate to a linear algebra class the computation time of solving systems of linear equations via LU factorization versus via matrix inversion by naive methods; to make the case for LU, I have to avoid various optimized algorithms built into SAGE. (Perhaps I should be using a call to LAPACK or something for this demonstration?)Greg MarksFri, 08 Feb 2013 21:53:18 +0100https://ask.sagemath.org/question/9787/