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.Sat, 28 Aug 2021 23:35:53 +0200Integer arithmetic performancehttps://ask.sagemath.org/question/58722/integer-arithmetic-performance/Hi!
I think Python/Sage is really slow with integer arithmetic. I have an example below that can illustrate this.
My question is why is this the case, and is there some way to improve it?
(My guess is this is probably due to memory allocation, i.e., for large integers the operations are not performed in place. But I tried the mutable integer type `xmpz` from the library `gmpy2`, and I don't see any improvement in performance... Also I'm curious how are the integers in Sage handled by default: does it use the GMP or FLINT library?)
---
Here is the example.
Given a list of integers, I want to compute the sum of the products of all its k-combinations. The naive solution is `sum(prod(c) for c in Combinations(vec, k))`. But the performance of this is not very good. Here is a version to do the enumeration of combinations manually.
def sum_c(k, w):
def dfs(k, n):
if k < 1:
ans[0] += pp[0]
else:
for m in range(k, n+1):
pp[k-1] = pp[k] * w[m-1]
dfs(k-1, m-1)
ans, pp = [0], [0]*k + [1]
dfs(k, len(w))
return ans[0]
from time import time
t = time()
sum_c(8, list(range(1, 31)))
print("sum_c:\t", time() - t)
from sage.all import *
t = time()
sum(prod(c) for c in Combinations(range(1, 31), 8))
print("naive:\t", time() - t)
The speed doubled with `sum_c`.
sum_c: 2.283874988555908
naive: 5.798710346221924
But with C this can be computed in less than 0.1s...
---
**Edit.** OK I tried `Cython` and `gmpy2`, and I'm able to get a satisfactory result for my problem.
Still I wonder if there were any way to improve the performance without doing something so "manual"...
And here is my "translation" for reference.
# distutils: libraries = gmp
from gmpy2 cimport *
import numpy as np
import_gmpy2()
cdef extern from "gmp.h":
void mpz_init(mpz_t)
void mpz_init_set_si(mpz_t, long)
void mpz_set_si(mpz_t, long)
void mpz_add(mpz_t, mpz_t, mpz_t)
void mpz_mul_si(mpz_t, mpz_t, long)
cdef dfs(long k, long n, list w, mpz ans, mpz[:] pp):
cdef long m
if k < 1:
mpz_add(ans.z, ans.z, pp[0].z)
else:
for m in range(k, n+1):
mpz_mul_si(pp[k-1].z, pp[k].z, w[m-1])
dfs(k-1, m-1, w, ans, pp)
def sum_c(long k, list w):
cdef long i
cdef mpz ans = GMPy_MPZ_New(NULL)
cdef mpz[:] pp = np.array([GMPy_MPZ_New(NULL) for i in range(k+1)])
mpz_init(ans.z)
for i in range(k):
mpz_init(pp[i].z)
mpz_init_set_si(pp[k].z, 1)
dfs(k, len(w), w, ans, pp)
return int(ans)8d1hSat, 28 Aug 2021 23:35:53 +0200https://ask.sagemath.org/question/58722/why can't I compute the zeros of an integer polynomial using solve()?https://ask.sagemath.org/question/57833/why-cant-i-compute-the-zeros-of-an-integer-polynomial-using-solve/ This works fine, producing complex roots:
x=var('x')
f=x+x**2+x**3-100
z=solve(f==0,x)
this also works fine:
R.<x>=ZZ[]
f=x+x**2+x**3-100
f.roots()
but this seems to run forever without error message and I don't understand why:
x=var('x',domain=ZZ)
f=x+x**2+x**3-100
z=solve(f==0,x)
can anyone explain or tell me where to start reading to understand this behaviour?
dantetanteThu, 01 Jul 2021 08:12:48 +0200https://ask.sagemath.org/question/57833/difference Python and Sage - integer and rational numberhttps://ask.sagemath.org/question/56110/difference-python-and-sage-integer-and-rational-number/in Python, if k is an integer, equation k / 4 returns the integer part of k over 4, while in Sage, it returns a rational.
How to work in Sage and change from result od divide from rational to like in Python ?
example: python
5 divide by 3 = 1
5 divide by 2 = 2
4 divide by 2 = 2MiroslawWed, 10 Mar 2021 22:48:57 +0100https://ask.sagemath.org/question/56110/Error with matrix definition of a linear programhttps://ask.sagemath.org/question/55970/error-with-matrix-definition-of-a-linear-program/ According to the folloing tract `https://trac.sagemath.org/ticket/16714`
this command works
p = MixedIntegerLinearProgram()
x = p.new_variable()
p.add_constraint(A_matrix*x <= a_vector)
so why the following code returns an error ?
A=[[1,0,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,0,0,1,0,0,0,0,0],[0,0,1,0,0,0,0,0,0,1,0,0],[0,0,0,0,1,0,0,1,0,0,0,0],[0,0,0,0,0,1,0,0,0,0,1,0],[0,0,0,0,0,0,0,0,1,0,0,1]]
U1=[1,1,1,1,1,1]
show(matrix(A))
show(vector(U1))
p = MixedIntegerLinearProgram(binary = true)
x = p.new_variable()
p.add_constraint(A*x <= U1)
p.show()
CyrilleMon, 01 Mar 2021 12:04:34 +0100https://ask.sagemath.org/question/55970/TypeError in parametric_plot3d with real or imaghttps://ask.sagemath.org/question/55824/typeerror-in-parametric_plot3d-with-real-or-imag/The code to plot a surface using `parametric_plot_3d`:
var("u,v")
parametric_plot3d([sqrt(u + I*v).real(), sqrt(u + I*v).imag(),v],(u,-1,1), (v,-1,1))
The full traceback of the error is quite long, so I give only the first few lines and last few lines:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-...-....> in <module>
----> 1 parametric_plot3d([sqrt(u + I*v).real(), sqrt(u + I*v).imag(),v],(u,-Integer(1),Integer(1)), (v,-Integer(1),Integer(1)))
.../sage/misc/decorators.py in wrapper(*args, **kwds)
649 kwds[new_name] = kwds[old_name]
650 del kwds[old_name]
--> 651 return func(*args, **kwds)
652
653 return wrapper
...
.../sage/rings/number_field/number_field_element.pyx in sage.rings.number_field.number_field_element.NumberFieldElement.__float__ (build/cythonized/sage/rings/number_field/number_field_element.cpp:19236)()
1908 if c.imag == 0:
1909 return c.real
-> 1910 raise TypeError('unable to coerce to a real number')
1911
1912 def _complex_double_(self, CDF):
TypeError: unable to coerce to a real number
Edit: I am also getting similar errors using the `log` function, `arctan` function, etc.debojit2178Tue, 23 Feb 2021 08:06:05 +0100https://ask.sagemath.org/question/55824/Integer programming bi-indexed variables.https://ask.sagemath.org/question/55872/integer-programming-bi-indexed-variables/Many integer programming programs as the following needed for Kemeny ranking
$$
\begin{array}{c}
\text{minimiser} \sum_{i,j \in \mathcal{A}}\omega_{i,j} x_{i,j}+\omega_{j,i} x_{j,i}\\\\
\text{sous les contraintes} \\\\
x_{i,j}+ x_{j,i} = 1, \forall i \not=j\\\\
x_{i,j}+ x_{j,k}+ x_{k,i}\geq 1, \forall i \not=j\not=k\not=i
\end{array}
$$
I want to construct a function wich takes the vector or the list $\omega$ and return the solution. But to construct such a function iot will be safer for me not to be obliged to assign on variable with a index to all two indexed variables.
Is there a way ? My problem is in the enumeration of the constraints for high indexes.CyrilleWed, 24 Feb 2021 10:41:01 +0100https://ask.sagemath.org/question/55872/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/Mistake in SageMathCell code, finding integral points on elliptic curveshttps://ask.sagemath.org/question/48933/mistake-in-sagemathcell-code-finding-integral-points-on-elliptic-curves/ I've the following number:
$$12\left(n-2\right)^2x^3+36\left(n-2\right)x^2-12\left(n-5\right)\left(n-2\right)x+9\left(n-4\right)^2\tag1$$
Now I know that $n\in\mathbb{N}^+$ and $n\ge3$ (and $n$ has a given value) besides that $x\in\mathbb{N}^+$ and $x\ge2$.
I want to check if the number is a perfect square, so I can rewrite $(1)$ as follows:
$$y^2=12\left(n-2\right)^2x^3+36\left(n-2\right)x^2-12\left(n-5\right)\left(n-2\right)x+9\left(n-4\right)^2\tag2$$
Where $y\in\mathbb{Z}$.
In this problem I've: $n=71$, the number is equal to;
$$y^2=57132x^3+2484x^2-54648x+40401\tag3$$
So, I used SageMathCell to look for the integral points on the elliptic curve and the code that was used is the following:
E = EllipticCurve([0, β, 0, γ, δ])
P = E.integral_points()
for p in P:
if p[0] % α == 0:
print(p[0] // α, p[1] // α)
I found the coeficients I need to use using equation $(2)$ and $(3)$ (but I do not know if they are corect):
- $$\alpha=12(71-2)^2=57132\tag4$$
- $$\beta=36(71-2)=2484\tag5$$
- $$\gamma=-144(71-5)(71-2)^3=-3122149536\tag6$$
- $$\delta=1296(71-4)^2(71-2)^4=131871507195024\tag7$$
So the final code looks like:
E = EllipticCurve([0, 2484, 0, -3122149536, 131871507195024])
P = E.integral_points()
for p in P:
if p[0] % 57132 == 0:
print(p[0] // 57132, p[1] // 57132)
But I found no solutions and it should give at least one solution at $x=1585$.
>What mistake have I made?Jan123Tue, 03 Dec 2019 17:13:08 +0100https://ask.sagemath.org/question/48933/Sage is not preparsing Python 3 underscored integershttps://ask.sagemath.org/question/47908/sage-is-not-preparsing-python-3-underscored-integers/Hello, Sage community!
With the upcoming migration of Sage from Python 2 to Python 3 (really soon, let us hope!), there are some testings I have been trying, and I have noticed that the "underscored integer literals", like "1_000_000" are not preparsed by Sage. For example,
preparse('1_000_000 + 3')
results in
'1_000_000 + Integer(3)'
However,
preparse('1000000 + 3')
returns
'Integer(1000000) + Integer(3)'
On the other hand, if I write
type(1_000_000 + 3)
the result is
<class 'sage.rings.integer.Integer'>
which is great, but
type(1_000_000 + 3_000)
instead gives me
<class 'int'>
Finally,
type(1000000 + 3000)
gives us
<class 'sage.rings.integer.Integer'>
I know one of the reasons for the `Integer` type was to allow divisions like `3/2` to return the float `1.5` even with Python 2, which would return (very disturbingly) `1`, in other case. However, Python 3 integers already do this. Besides what I mentioned above and this, I haven't found any other difference in behavior.
So I was wondering: Is there any disadvantage in Sage not being preparsing this type of literals?dsejasFri, 13 Sep 2019 22:41:47 +0200https://ask.sagemath.org/question/47908/Request: Have the len function output a Sage Integer instead of a Python inthttps://ask.sagemath.org/question/48141/request-have-the-len-function-output-a-sage-integer-instead-of-a-python-int/In the following code (See https://sagecell.sagemath.org/?q=cctcfj ):
a=[4,5,6]
b=[0,1,2]
for i in zip([0,1,2],a):
print i[0],"divided by",len(a),"is equal to",i[0]/len(a)
a=[4,5,6]
b=range(len(a))
print(b)
for i in zip(b,a):
print i[0],"divided by",len(a),"is equal to",i[0]/len(a)
Gives the following output
0 divided by 3 is equal to 0
1 divided by 3 is equal to 1/3
2 divided by 3 is equal to 2/3
[0, 1, 2]
0 divided by 3 is equal to 0
1 divided by 3 is equal to 0
2 divided by 3 is equal to 0
Greetings
-AAdrian sotoWed, 02 Oct 2019 16:02:50 +0200https://ask.sagemath.org/question/48141/Where is defined __gmpq_cmp_z?https://ask.sagemath.org/question/47314/where-is-defined-__gmpq_cmp_z/I got the following error after launching sage in Debian10.
----> 7 cdef class Integer(EuclideanDomainElement):
global cdef = undefined
global Integer = undefined
global EuclideanDomainElement = undefined
8 # This is really of type mpz_t, but we don't use the mpz_t typedef
9 # to work around Cython bug
11 cdef __mpz_struct value[1]
12
13 cdef int _to_ZZ(self, ZZ_c *z) except -1
14 cdef void set_from_mpz(self, mpz_t value)
15 cdef hash_c(self)
16
17 cpdef __pari__(self)
18
19 cpdef _shift_helper(Integer self, y, int sign)
20 cpdef _add_(self, other)
21 cpdef _mul_(self, other)
22 cpdef _pow_(self, other)
23 cdef _and(Integer self, Integer other)
24 cdef _or(Integer self, Integer other)
25 cdef _xor(Integer self, Integer other)
26
27 cpdef size_t _exact_log_log2_iter(self,Integer m)
28 cpdef size_t _exact_log_mpfi_log(self,m)
29 cpdef RingElement _valuation(Integer self, Integer p)
30 cdef object _val_unit(Integer self, Integer p)
31 cdef Integer _divide_knowing_divisible_by(Integer self, Integer right)
ImportError: /usr/lib/python2.7/dist-packages/sage/rings/integer.x86_64-linux-gnu.so: undefined symbol: __gmpq_cmp_z
Have you any idea to solve this error? Thank you.fylouTue, 30 Jul 2019 19:25:19 +0200https://ask.sagemath.org/question/47314/integer digits range problem (see sage error below) Thanks!!!https://ask.sagemath.org/question/46782/integer-digits-range-problem-see-sage-error-below-thanks/.
sage: for i in [9,10,11]:
....: i.digits(base=3)
....:
[0, 0, 1]
[1, 0, 1]
[2, 0, 1]
sage: for i in range(9,12):
....: i.digits(base=3)
....:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-2-e5aab74726b7> in <module>()
1 for i in range(Integer(9),Integer(12)):
----> 2 i.digits(base=Integer(3))
3
AttributeError: 'int' object has no attribute 'digits'
sage: [9,10,11]==range(9,12)
TrueNewtonTue, 04 Jun 2019 03:07:14 +0200https://ask.sagemath.org/question/46782/Convert real matrix into Integer matrixhttps://ask.sagemath.org/question/45203/convert-real-matrix-into-integer-matrix/Suppose I have a real matrix with integer entries
A = matrix(RR,[[1,2,3],[4,5,6]])
I would like to convert it to an Integer matrix (ZZ). I can do it element by element but is there a function that will do this for the entire matrix. Doing B=ZZ(A) will return an error message
unable to coerce <type 'sage.matrix.matrix_generic_dense.Matrix_generic_dense'> to an integer.
raykanSun, 27 Jan 2019 16:34:47 +0100https://ask.sagemath.org/question/45203/Finding coprime integers near a lattice pointhttps://ask.sagemath.org/question/44435/finding-coprime-integers-near-a-lattice-point/ I have a list $L$ of ordered pairs $(n,m)$ where $n$ and $m$ are integers. I would like to know which elements $(n,m)$ in $L$ satisfy the property that $\gcd(n+i,m+j) \neq 1$ for $i =-1,0,1$ and $j =-1,0,1.$ For example the point $(55,21)$ has this property since $[(55+i,21+j) ] = [(54,20),(54,21),(54,22),(55,20),(55,21),(55,22),(56,20),(56,21),(56,22)].$ I have tried the following :
`for (n,m) in L:
for i in range(-1,2):
for j in range(-1,2):
if gcd(n+i,m+j)!=1:
print(n,m)`
which returns any point with $gcd =1$ which is not what I want.
Thanks very much for your help!
cihanMon, 26 Nov 2018 03:58:03 +0100https://ask.sagemath.org/question/44435/Evaluate from string an equation that has integer divisionhttps://ask.sagemath.org/question/44328/evaluate-from-string-an-equation-that-has-integer-division/ I have the following Python list that contains strings of equations.
L = ['651/349*t + 5382747/9778631000', 't + 57879/196133000', '1000/349*t + 57879/68450417']
You can see that all of the equations have integer division. Because this is obtained by some program, I can not edit the strings.
When I evaluate for `t=1.0` with the following code in SageMath (for example), it does not evaluate as an Euclidean division.
F = function('F')(t)
for k in L:
F(t) = eval(k)
Fc = fast_callable(F, vars=[t])
val2eval = 1.0
print(Fc(val2eval).n(13))
It gives
1.00000000000000
1.00000000000000
2.00000000000000
And should be give
1.86587997307599
1.00029510077345
2.86617507384944
Of course I can solve this by modifying MANUALLY the strings of the equations by indicating that the denominator is a real number and not an integer (I put a decimal point at the end of the integer in the denominator) as following.
L = ['651/349.*t + 5382747/9778631000.', 't + 57879/196133000.', '1000/349.*t + 57879/68450417.']
But this is not the idea, the strings of the equations are generated automatically and one can not modify by editing manually, because it will be implemented in a process where it should be create at least 2000 equations.
Is there some elegant solution for this? --Many thanks!loSuarezBSun, 18 Nov 2018 18:21:18 +0100https://ask.sagemath.org/question/44328/How to compute on Cython mode with 64-bit int?https://ask.sagemath.org/question/43832/how-to-compute-on-cython-mode-with-64-bit-int/The computation is on SageMath 8.3, on a 64-bit computer.
If the integers are less than $2^{31}$ everything is alright:
sage: %time champions(2**30,2**30+10)
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 2.15 ms
But if the integers are greater than $2^{31}$, there is a problem `OverflowError: value too large to convert to int`.
sage: champions(2**31,2**31+10)
---------------------------------------------------------------------------
OverflowError Traceback (most recent call last)
<ipython-input-7-2a762f4cafd8> in <module>()
----> 1 champions(Integer(2)**Integer(31),Integer(2)**Integer(31)+Integer(10))
/home/sage/.sage/temp/LAPTOP-7O5QV19T/9856/spyx/_home_sage_SAGE_EulerRH_spyx/_home_sage_SAGE_EulerRH_spyx_0.pyx in _home_sage_SAGE_EulerRH_spyx_0.champions()
12 return len(list(factor(n)))
13
---> 14 cpdef champions(int m1, int m2):
15 cdef int n,o,s,p,pr
16 cdef float a,c
OverflowError: value too large to convert to int
Here is the code:
from sage.all import *
cpdef g(float x):
return x/(exp(float(euler_gamma))*ln(ln(x)))
cpdef omega(int n):
return len(list(factor(n)))
cpdef champions(int m1, int m2):
cdef int n,o,s,p,pr
cdef float a,c
a=1.7683358; s=2; p=3; pr=6; n=m1
while n<=m2:
if mod(n,10**7)==0:
print(n)
if n>pr:
p=next_prime(p); pr*=p; s+=1
o=omega(n)
if n<>pr:
c=(euler_phi(n)/g(float(n)))**(1/float(s-o))
if c>a:
a=c
print([n,a,factor(Integer(pr)/Integer(n))])
n+=1Sébastien PalcouxFri, 05 Oct 2018 11:52:59 +0200https://ask.sagemath.org/question/43832/NameError: name 'Integer' is not definedhttps://ask.sagemath.org/question/35506/nameerror-name-integer-is-not-defined/ Hi,
all of a sudden, I'm experiencing a strange error and cannot find any solution for it.
Sage itself works fine, but as soon as I try to load any .sage file, the application can't start. Inside sage I can do any calculation/operation as usual, but if I for example load an application that contains:
a=1
b=2
sage returns:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-496f9e9073df> in <module>()
----> 1 load("u.sage")
sage/structure/sage_object.pyx in sage.structure.sage_object.load (/build/sagemath/src/sage-7.4/src/src/build/cythonized/sage/structure/sage_object.c:12333)()
/usr/lib/python2.7/site-packages/sage/repl/load.pyc in load(filename, globals, attach)
245 if attach:
246 add_attached_file(fpath)
--> 247 exec(preparse_file(open(fpath).read()) + "\n", globals)
248 elif ext == '.spyx' or ext == '.pyx':
249 if attach:
/usr/lib/python2.7/site-packages/sage/structure/sage_object.so in <module>()
NameError: name 'Integer' is not defined
Yesterday everything was working fine. I hadn't done any system upgrades and the error appears on programs written and working yesterday and on new written programs.
Does anyone know how to solve this error or where it suddenly comes from? A restart didn't change anything...0x22Thu, 10 Nov 2016 15:25:50 +0100https://ask.sagemath.org/question/35506/simplifying out negative signs in exponentshttps://ask.sagemath.org/question/43132/simplifying-out-negative-signs-in-exponents/Hello all!
I can't for the life of me find a way to force sage to return terms with only positive coefficient variable exponents. For example, if I enter something like
assume(n, 'integer', n>10)
c = 2^(-n)
I would like the output to be something like `1/(2^n)`, but instead I can only get something like `2^(-n)`. Is there a way to force the output to display only positive coefficients in front of the n?
In general I'd like some `magicFunc` function which I could feed some expression `g(x,n)` and have it return a rational expression with no negatives; eg.
var('x,n')
assume(x,'real')
assume(n,'integer',n>10)
g(x,n) = 2^(-n)*x^(-3*n)*3^n
magicFunc(g(x,n))
Would return `3^n/(2^n*x^(3n))`
Is this possible? This seems like it should be an existent simplification method, but nothing I've tried seems to work.
Thanks!Jason021Tue, 24 Jul 2018 23:19:26 +0200https://ask.sagemath.org/question/43132/n-th power of matriceshttps://ask.sagemath.org/question/35155/n-th-power-of-matrices/Is there any way to calculate the n-th power of a (upper unitriangular) matrix in Sage? Here n is an integer variable.
For example, if y=matrix([[1,0,0],[0,1,1],[0,0,1]]), then I want to obtain a formula in n for y^n. In this case this would be y^n=matrix([[1,0,0],[0,1,n],[0,0,1]]).
I tried the following:
sage: y=matrix([[1,0,0],[0,1,1],[0,0,1]]); var('n');
sage: y^n
This resulted in the error: "NotImplementedError: non-integral exponents not supported"
Adding
sage: assume(n, 'integer')
has no effect at all.irisSun, 16 Oct 2016 10:56:39 +0200https://ask.sagemath.org/question/35155/local variable 'Integer' referenced before assignmenthttps://ask.sagemath.org/question/41524/local-variable-integer-referenced-before-assignment/ I'll be honest I have no idea why this error is popping up, and it's really weird! I'm writing code that will generate a closed form solution to the partial sums of integer powers up to n, and this is what I have
def sum_first_n_p_powers(p):
length = p+1
vector = zero_vector(length)
matrix_list = []
for x in xrange(0,length):
copy = vector[:]
for y in xrange(0,length):
copy[y] = binomial(length-y,x-y+1)
matrix_list.append(copy)
M = Matrix(matrix_list)
solution_vector = zero_vector(length)
solution_vector[0] = 1
coeffs = M.solve_right(solution_vector)
n = var('n')
0 = polynomial
for x in xrange(0,len(coeffs)):
polynomial = polynomial + coeffs[x]*n^(length-x)
return polynomial
And when I try to run it I get the most unusual error, it just says to me
UnboundLocalError: local variable 'Integer' referenced before assignment.
I have never run into this before and have no idea what's wrong with the line. Thanks in advance!
JRHalesWed, 14 Mar 2018 02:12:23 +0100https://ask.sagemath.org/question/41524/unable to coerce <type 'sage.rings.real_mpfi.RealIntervalFieldElement'> to an integerhttps://ask.sagemath.org/question/38338/unable-to-coerce-type-sageringsreal_mpfirealintervalfieldelement-to-an-integer/ I am very desperate. I just want to convert a real number to an integer. I have tried int(x), Integer(x), floor(x), ceil(x) but nothing seems to work.davidThu, 20 Jul 2017 23:11:57 +0200https://ask.sagemath.org/question/38338/Matrix conjugacy classes over Z and ideal classeshttps://ask.sagemath.org/question/8244/matrix-conjugacy-classes-over-z-and-ideal-classes/I had a couple questions; the first involves matrix conjugacy classes over the integers and the second involves integral bases. I'm not sure what the algorithms in Sage are for the following procedures.
1) Is it possible to determine if two integer-valued square matrices (which are conjugate over Q) are also conjugate over Z?
2) In a number field K, given an ideal class I, we can find an integral basis for a representative ideal in I by the command:
sage: I.integral_basis()
Is it possible to work in the reverse direction, that is given a set of elements in K which form an integral basis, is it possible to find the corresponding ideal and ideal class for that integral basis?
Thanks in advance for any advice.CCThu, 28 Jul 2011 21:14:45 +0200https://ask.sagemath.org/question/8244/solve x^y == z (for x)https://ask.sagemath.org/question/35105/solve-xy-z-for-x/
I don't understand the behavior:
> var('x','y','z'); assume(x>0, y>0, z>0); assume(x,y,z, 'real')
> solve(x^y==z, x)
generates a traceback error:
"...
Is y an integer?"
I can get the expected answer after adding
> assume(y, 'integer')
but this seems like it should be unnecessary. Anyone know what is going on here?
thanks,
Dustindnlennonpu01Mon, 10 Oct 2016 09:13:03 +0200https://ask.sagemath.org/question/35105/Testing if a result n is an Integer, for large n.https://ask.sagemath.org/question/34406/testing-if-a-result-n-is-an-integer-for-large-n/ I have a number x of size 2^160, and I perform the operation n = x*(x+1.5) and want to test if the result is an integer.
In python I would normally try, n.is_integer() or use an isinstance(), but this doesn't work in sage, I assume due to the fact sage integers are set up quite differently.
Upon scouring this site, I found someone recommend n is in ZZ, but this doesn't work (sage seems to loose accuracy at this level)
Example:
n = 2^160
n in ZZ
Result: False
The only (terribly inefficient) way I can get this to work is to call n.divisors() and if I get the error
"AttributeError: 'sage.rings.real_mpfr.RealNumber' object has no attribute 'divisors' "
I know it was indeed not an integer.
There must be a better way?
jbeatzWed, 10 Aug 2016 14:03:46 +0200https://ask.sagemath.org/question/34406/Assume that n is positive integerhttps://ask.sagemath.org/question/33181/assume-that-n-is-positive-integer/ It seems I cannot make Sage assume that the variable n is a positive integer.
var('n')
assume(n, 'integer')
assume(n>0)
In this code, the "n>0" overwrites the assumption that n is an integer. The command
n.is_integer()
returns false. How do I do this?KofiFri, 22 Apr 2016 11:24:24 +0200https://ask.sagemath.org/question/33181/Possible bug of sum functionhttps://ask.sagemath.org/question/33068/possible-bug-of-sum-function/Consider the following code:
def s(n):
return sum(k/n for k in range(n + 1))
L0 = s(2)
for n in range(2, 3):
L1 = s(n)
The answers are (using sage 7.1):
print L0, L1
(3/2, 1)
In the second case sage is using the usual integer division of python 2.x while in the first one it is using the exact representation of rationals. Is this a known bug?
jllbMon, 11 Apr 2016 19:15:50 +0200https://ask.sagemath.org/question/33068/range and division : unexpected behaviorhttps://ask.sagemath.org/question/32891/range-and-division-unexpected-behavior/Consider the following snippet :
N=5
# code 1
for n in range(N,N+1):
for k in range(0,n):
print k/n
print '-'*10
# code 2
n=N
for k in range(0,n):
print k/n
I was expecting code 1 and code 2 to print the same output. This is not the case :
0
0
0
0
0
----------
0
1/5
2/5
3/5
4/5
In the first case, `k/n` is Python-evaluated as an integer division, in the second case, `k/n` is Sage-evaluated as a fraction. Can someone elaborate please ?
I only notice that substituting `srange(N,N+1)` to `range(N,N+1)` fixes the problem.
candideSun, 27 Mar 2016 11:28:01 +0200https://ask.sagemath.org/question/32891/Integer result for fractionhttps://ask.sagemath.org/question/32347/integer-result-for-fraction/ Hi!
Can somebody explain me this strange behavior of Sage :
for p in range(1,10):
for q in range(1,10):
print p/q
Then `p/q` return the integer division.
However:
for p in range(1,10):
print p/7
give rational results.
A solution is to use `Rational(p)/Rational(q)` instead of `p/q`. But it is not an explanation.
Thanks,
Arnaud
Arnaud1418Wed, 27 Jan 2016 20:12:43 +0100https://ask.sagemath.org/question/32347/'Integer' object is not callable error when it doesn't appear as though I'm calling an integerhttps://ask.sagemath.org/question/29983/integer-object-is-not-callable-error-when-it-doesnt-appear-as-though-im-calling-an-integer/ I have a cell where I'm trying to make a recursive function to shortcut Newton's Method, and it appears to be written properly, but I keep getting the error shown above
%auto
#don't call this, it's an internal function that the main one calls for its recursion step
def newtonsMethodRecursiveCall(func, deri, start, iters):
if iters == 0:
return start - (func(start) / deri(start))
else:
r = newtonsMethodRecursiveCall(start, func, deri, iters-1)
return r - (func(r) / deri(r))
# Recursive function to perform Newton's Method to the nth degree
def newMet(func, vari, start, iters = 10):
deri(vari) = derivative(func, vari, 1)
return (newtonsMethodRecursiveCall(func, deri, start, iters))
when I tested with
tf(x) = x^2 - 2
newMet(tf, x, 1)
it gave me the error.
I don't see anywhere that should indicate that I would be calling an integer, I thought I'd checked all of the names to make sure they were undefined before attempting to call them as a function
as a side note, I don't care if there's already a function for what I'm doing, I wanted to try to write one myself using the definition of newton's methodMFriendWed, 14 Oct 2015 03:49:11 +0200https://ask.sagemath.org/question/29983/How to cast a string with an exponent from sys.argv to an Integer ?https://ask.sagemath.org/question/29597/how-to-cast-a-string-with-an-exponent-from-sysargv-to-an-integer/Hi,
For an exercise, I have written a Python script that takes an integer argument. Of course, the input in sys.argv is of type 'str', so I cast it to an Integer. It works, but I am supposed to accept numbers written like '123^1237' too, with a hat for the exponent. And I cannot find how to do that. In the sage interpreter, I can type "n = Integer(123^1237)" without any problem, but in my script it fails with a "TypeError: unable to convert '123^1237' to an integer". ThanksOnoxSat, 26 Sep 2015 17:00:01 +0200https://ask.sagemath.org/question/29597/