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.Wed, 09 Nov 2022 17:37:56 +0100Inconsistent/incorrect value of limit involving tan and tanhhttps://ask.sagemath.org/question/64794/inconsistentincorrect-value-of-limit-involving-tan-and-tanh/Out of sheer curiosity I tried to compute $\lim_{x \rightarrow \infty} \frac{d}{dx} \log \tan (\frac \pi 2 \tanh x)$, and found that the maxima engine disagrees on how to take the limit. I am not particularly great at math but I thought it would be interesting to "compare" the horizontal and vertical asymptotes of tanh and tan like this.
It returns something different for the original expression within the limit versus `simplify_full`, `reduce_trig`, and `exponentialize`. Other algorithms variously either fail or return 2, but maxima will confidently report `0` if the expression is not simplified. Presumably it is tempted by the division-by-infinity and multiplication-by-zero, but isn't that the point of taking limits?
sage: fun = diff(log(tan(pi/2 * tanh(x))), x)
sage: simplifications = [lambda x: x, attrcall('simplify_full'), attrcall('reduce_trig'), attrcall('exponentialize')]
sage: algorithms = ['maxima', 'giac', 'fricas', 'mathematica_free']
sage: for simplification in simplifications:
....: simplified = simplification(fun)
....: print("Simplified:", simplified)
....: for algorithm in algorithms:
....: print(algorithm, limit(simplified, x=infinity, algorithm=algorithm))
....: print()
....:
Simplified: -1/2*pi*(tan(1/2*pi*tanh(x))^2 + 1)*(tanh(x)^2 - 1)/tan(1/2*pi*tanh(x))
maxima 0
giac 2
fricas failed
mathematica_free 2
Simplified: 1/2*pi/(cos(1/2*pi*sinh(x)/cosh(x))*cosh(x)^2*sin(1/2*pi*sinh(x)/cosh(x)))
maxima 1/2*pi*limit(1/(cos(1/2*pi*sinh(x)/cosh(x))*cosh(x)^2*sin(1/2*pi*sinh(x)/cosh(x))), x, +Infinity)
giac 2
fricas failed
mathematica_free 2
Simplified: 1/2*pi*cot(1/2*pi*tanh(x))*sec(1/2*pi*tanh(x))^2*sech(x)^2
maxima und
giac 2
fricas failed
mathematica_free 2
Simplified: -1/2*pi*((e^(-x) - e^x)^2/(e^(-x) + e^x)^2 - 1)*((I*e^(1/2*I*pi*e^(-x)/(e^(-x) + e^x) - 1/2*I*pi*e^x/(e^(-x) + e^x)) - I*e^(-1/2*I*pi*e^(-x)/(e^(-x) + e^x) + 1/2*I*pi*e^x/(e^(-x) + e^x)))^2/(e^(1/2*I*pi*e^(-x)/(e^(-x) + e^x) - 1/2*I*pi*e^x/(e^(-x) + e^x)) + e^(-1/2*I*pi*e^(-x)/(e^(-x) + e^x) + 1/2*I*pi*e^x/(e^(-x) + e^x)))^2 + 1)*(e^(1/2*I*pi*e^(-x)/(e^(-x) + e^x) - 1/2*I*pi*e^x/(e^(-x) + e^x)) + e^(-1/2*I*pi*e^(-x)/(e^(-x) + e^x) + 1/2*I*pi*e^x/(e^(-x) + e^x)))/(I*e^(1/2*I*pi*e^(-x)/(e^(-x) + e^x) - 1/2*I*pi*e^x/(e^(-x) + e^x)) - I*e^(-1/2*I*pi*e^(-x)/(e^(-x) + e^x) + 1/2*I*pi*e^x/(e^(-x) + e^x)))
maxima 2
giac 2
fricas failed
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In [105], line 5
3 print("Simplified:", simplified)
4 for algorithm in algorithms:
----> 5 print(algorithm, limit(simplified, x=infinity, algorithm=algorithm))
6 print()
File /usr/lib/python3.10/site-packages/sage/calculus/calculus.py:1461, in limit(ex, dir, taylor, algorithm, **argv)
1459 l = libgiac.limit(ex, v, a, -1).sage()
1460 elif algorithm == 'mathematica_free':
-> 1461 return mma_free_limit(ex, v, a, dir)
1462 else:
1463 raise ValueError("Unknown algorithm: %s" % algorithm)
File /usr/lib/python3.10/site-packages/sage/calculus/calculus.py:1510, in mma_free_limit(expression, v, a, dir)
1508 raise ValueError('wrong input for limit')
1509 json_page_data = request_wolfram_alpha(input)
-> 1510 all_outputs = parse_moutput_from_json(json_page_data)
1511 if not all_outputs:
1512 raise ValueError("no outputs found in the answer from Wolfram Alpha")
File /usr/lib/python3.10/site-packages/sage/interfaces/mathematica.py:1284, in parse_moutput_from_json(page_data, verbose)
1282 queryresult = page_data['queryresult']
1283 if not queryresult['success']:
-> 1284 raise ValueError('asking wolframalpha.com was not successful')
1285 if 'pods' not in queryresult:
1286 raise ValueError('json object contains no pods')
ValueError: asking wolframalpha.com was not successful
The sympy algorithm was excluded from the above because it seems to be much worse behaved than the others. For the same suite of simplifications above, it respectively returns [hangs forever], 2, "conversion to SageMath is not implemented", "maximum recursion depth exceeded".
Is the maxima behaviour here a bug, and if so, where should I report it? (And if anyone off the top of their head knows any interesting identities around this expression, that would be cool too 🙂)scoreWed, 09 Nov 2022 17:37:56 +0100https://ask.sagemath.org/question/64794/define a finite semiringhttps://ask.sagemath.org/question/63217/define-a-finite-semiring/What would be the simplest way to define the semiring with elements $\\{0, 1\\}$ with the logical OR ($|$) operation as addition and the standard integer multiplication?
At very least it should be accepted by `PolynomialRing` as the domain for coefficients.Max AlekseyevMon, 11 Jul 2022 22:45:31 +0200https://ask.sagemath.org/question/63217/In SageMath 9.2 :"TypeError: unable to make sense of Maxima expression" .What does it mean ?https://ask.sagemath.org/question/64386/in-sagemath-92-typeerror-unable-to-make-sense-of-maxima-expression-what-does-it-mean/ is there anyone who would help me with the output of this system?
import time
Start_Time = time.time()
var('N n k x h y X Y m K H s')
eq0 = N-187 == 0
eq1 = (-4-n^2+9*N+24*k*N-16*x-16*x^2+4*(h+2*h*x)^2+n*(2-4*y))/8 == 0
eq2 = -4*sqrt(-(N*(9+24*k)-3)/48) - h == 0
eq3 = (4*x+2)^2-(2*y-1)^2-N*(9+24*k) == 0
eq4 = x+h/4 == 0
eq5 = h^2-1-n == 0
eq6 = (-4-m^2+9*N+24*K*N-16*X-16*X^2+4*(H+2*H*X)^2+m*(2-4*Y))/8 == 0
eq7 = -4*sqrt(-(N*(9+24*K)-3)/48) - H == 0
eq8 = (4*X+2)^2-(2*Y-1)^2-N*(9+24*K) == 0
eq9 = X+H/4 == 0
eq10 = H^2-1-m == 0
eq11 = k+2*sqrt(-374*k-140)-374-K == 0
eq13 = (k-K)/2-(187-2*s) == 0
eq14 = 187*(9+24*k)-3+48*s^2 == 0
solutions = solve([eq0,eq1,eq2,eq3,eq4,eq5,eq6,eq7,eq8,eq9,eq10,eq11,eq13,eq14],N,n,k,x,h,y,X,Y,m,K,H,s)
sol = solutions
print(sol)
Execution_Time = time.time() - Start_Time
print (Execution_Time)
Periodic_1_6Tue, 11 Oct 2022 11:50:25 +0200https://ask.sagemath.org/question/64386/Determinants over cyclotomic fields are broken?https://ask.sagemath.org/question/64194/determinants-over-cyclotomic-fields-are-broken/ I launch the code below which generates two unimodular matrices L and U until it thinks that norm(det(L*U)) is not in [-1,1] which is probably a bug:
def seek_bug(K,n, rng=[-3,3], density=1.0):
print("Searching")
z=K.gen()
OK = K.fraction_field().ring_of_integers()
units = [z^((1-(i))/2) * (1-z^i)/(1-z) for i in list( range(1,K.degree(),2) ) ] if K.degree()>2 else [1,z]
assert( all([OK(u).is_unit() for u in units]) ), "Wrong units!"
L = Matrix.identity(K,n)
U = Matrix.identity(K,n)
for i in range(n):
for j in range(n):
if i<j:
if uniform(0,1)<density:
L[i,j]=OK.random_element(rng[0],rng[1])
elif j<i:
if uniform(0,1)<density:
U[n-j-1,n-i-1]=OK.random_element(rng[0],rng[1])
else:
U[i,i]*=prod([ units[randrange(len(units))] for i in range(6) ])
L[i,j]*=prod([ units[randrange(len(units))] for i in range(6) ])
B = L*U
if not( norm(det(B)) in [-1,1] ):
return L, U, B
return None, None, None
n=2
K.<z> = CyclotomicField(16)
L, U, B = None, None, None
while L is None:
L, U, B = seek_bug(K,n)
print(norm(det(L)), norm(det(U)))
assert det(L)*det(U) == det(L*U), "This should work... But it doesn't"
The last assertion fails which implies det(L)*det(U) != det(L*U) (Note: even without taking the norm!), but this should not be the thing. It fails in power-of-two cyclotomics. Did I make a mistake, or are the determinants in sage are broken?
Checked this on 3 machines with sage 9.4, 9.5 and 9.6: it fails everywhere.Alex KareninTue, 27 Sep 2022 09:36:54 +0200https://ask.sagemath.org/question/64194/saving animation problemhttps://ask.sagemath.org/question/63317/saving-animation-problem/ sines = [plot(c*sin(x), (-2*pi,2*pi), color=Color(c,0,0), ymin=-1, ymax=1) for c in srange(0,1,.1)]
a = animate(sines)
a.save('animations/sines')
When running this code I get the following error:
*Error: Cannot generate GIF animation. The convert command (ImageMagick) is present but does not seem to be functional. Verify that the objects passed to the animate command can be saved in PNG image format. See www.imagemagick.org more information.*
I can find the .gif in .sage/tmp/mymachine/44754 and move it, but using the save command would be much easier.
I am on Sagemath 9.5 and Ubuntu 22.04
AnnavwWed, 20 Jul 2022 08:56:09 +0200https://ask.sagemath.org/question/63317/LCM of 3 polynomialshttps://ask.sagemath.org/question/61522/lcm-of-3-polynomials/why changing the order of the parameters gives different reults ?
sage: x,y = var('x y')
sage: LCM([x^2 - y^2, x^2 + 2*x*y + y^2, x^3 + y^3])
(x^3 + y^3)*(x^2 + 2*x*y + y^2)*(x^2 - y^2)/(x + y)^2
sage: LCM([x^2 - y^2, x^3 + y^3, x^2 + 2*x*y + y^2])
(x^3 + y^3)*(x^2 + 2*x*y + y^2)*(x^2 - y^2)/(x + y)^3
mgonzalezmWed, 16 Mar 2022 03:20:43 +0100https://ask.sagemath.org/question/61522/Bug in series evaluated at 0https://ask.sagemath.org/question/61400/bug-in-series-evaluated-at-0/ Hello!
Here is a simple example of the problem I have found in sagemath:
var('x n')
print(sum(x^n/factorial(n), n, 0, Infinity))
x = 0
print(sum(x^n/factorial(n), n, 0, Infinity))
The first output is e^x (as expected), and the second output is 0, which I think should be 1, because $0^0=1$.
Since the general formula works for every nonzero x, and it also gives a result for x=0, I feel like this could be quite misleading in more complicated examples, where the result is not so obvious.
Or try this:
x = 0
print(sum(x^n, n, 0, Infinity))
print(sum(x^n, n, -1, Infinity))
Both outputs are 0, even though the first should be 1, and the second should be infinity/undefined.
The issue seems to be about powers of 0 in the sum.
Note that in the case of finite sums, both sum(0^n, n, 0, 5) and sum(0^n, n, -1, 5) produce errors, however sum([0^n for n in range(0,5)]) outputs 1.
This is probably related to trac.sagemath.org/ticket/22027.Roland765Sat, 05 Mar 2022 11:14:33 +0100https://ask.sagemath.org/question/61400/call to integrate with Fricas hangs but works inside Fricashttps://ask.sagemath.org/question/61090/call-to-integrate-with-fricas-hangs-but-works-inside-fricas/I noticed some calls to integrate using "fricas" algorithm (but possibly others also) hang when run from sagemath but the same integrate command works fast when run directly from Fricas on same computer.
I am running sagemath 9.5 on ArchLinux inside VBox machine. Here is an example.
>which sage
/bin/sage
>which fricas
/bin/fricas
>fricas --version
FriCAS 1.3.7
based on sbcl 2.2.1
>sage --version
SageMath version 9.5, Release Date: 2022-01-30
>
Now
>sage
┌────────────────────────────────────────────────────────────────────┐
│ SageMath version 9.5, Release Date: 2022-01-30 │
│ Using Python 3.10.2. Type "help()" for help. │
└────────────────────────────────────────────────────────────────────┘
sage: var("a b x d c e")
(a, b, x, d, c, e)
sage: integrand = x*(e *x^3 + d)/(c*x^6 + b*x^3 + a)
sage: fricas.setSimplifyDenomsFlag(fricas.true)
false
sage: anti = integrate(integrand, x, algorithm="fricas")
And the above hangs. I waited for more than 30 minutes. Now I run the same integrate inside Fricas itself, and it completes in less than 10-20 seconds. The output is very large, so I am wondering may be this is why sagemath hangs?
>fricas
Checking for foreign routines
FRICAS="/usr/lib/fricas/target/x86_64-linux-gnu"
spad-lib="/usr/lib/fricas/target/x86_64-linux-gnu/lib/libspad.so"
foreign routines found
openServer result 0
FriCAS Computer Algebra System
Version: FriCAS 1.3.7
Timestamp: Fri Feb 4 01:39:20 AM CST 2022
(1) -> setSimplifyDenomsFlag(true)
(3) -> integrand := x*(e *x^3 + d)/(c*x^6 + b*x^3 + a);
(4) -> integrate(integrand, x);
Type: Union(Expression(Integer),...)
(5) ->
Is there a limit on the output from integrate command and that is why it hangs?
In sagemath 9.3 this same command worked OK and did not hang. I have few others like this that now hang in 9.5
Any idea what is going on? Just in case this is a new bug, created a ticket https://trac.sagemath.org/ticket/33344#ticket
Thanks
--NasserNasserMon, 14 Feb 2022 20:26:19 +0100https://ask.sagemath.org/question/61090/Meijer G function in Sagehttps://ask.sagemath.org/question/60006/meijer-g-function-in-sage/ Hi,
I'm quite new to Sage so please forgive my naiveness.
I would need to check ( symbolically and numerically) some identities concerning the Meijer G function. I am aware that mpmath and sympy support this function, but I would like to remain within Sage.
Previous posts on this subject are quite old and from them I understood that importing from sympy does not provide a satisfactory integration into sage environment. Also they hint to the possibility that the function be implemented in Sage: yet could not find recent information on this.
Can somebody inform on the present stage ?
gcabMon, 29 Nov 2021 20:53:54 +0100https://ask.sagemath.org/question/60006/"SignalError: Illegal instruction" on calling .right_kernel()https://ask.sagemath.org/question/58775/signalerror-illegal-instruction-on-calling-right_kernel/**UPDATE.** I see the same problem in both Sage 9.3 and Sage 9.4 (but not in Sage 9.2), the screenlog below is for Sage 9.4.
I have a particular matrix on which computing `.right_kernel()` by Sage 9.4 results in `SignalError: Illegal instruction`.
How to deal with such an error?
sage: load("bug_illegal_kernel.sage")
---------------------------------------------------------------------------
SignalError Traceback (most recent call last)
<ipython-input-1-5e05d00e2706> in <module>
----> 1 load("bug_illegal_kernel.sage")
/usr/local/SageMath.94/local/lib/python3.9/site-packages/sage/misc/persist.pyx in sage.misc.persist.load (build/cythonized/sage/misc/persist.c:2563)()
171
172 if sage.repl.load.is_loadable_filename(filename):
--> 173 sage.repl.load.load(filename, globals())
174 return
175
/usr/local/SageMath.94/local/lib/python3.9/site-packages/sage/repl/load.py in load(filename, globals, attach)
270 add_attached_file(fpath)
271 with open(fpath) as f:
--> 272 exec(preparse_file(f.read()) + "\n", globals)
273 elif ext == '.spyx' or ext == '.pyx':
274 if attach:
<string> in <module>
/usr/local/SageMath.94/local/lib/python3.9/site-packages/sage/matrix/matrix2.pyx in sage.matrix.matrix2.Matrix.right_kernel (build/cythonized/sage/matrix/matrix2.c:31019)()
4715
4716 # Go get the kernel matrix, this is where it all happens
-> 4717 M = self.right_kernel_matrix(*args, **kwds)
4718
4719 ambient = R**self.ncols()
/usr/local/SageMath.94/local/lib/python3.9/site-packages/sage/matrix/matrix2.pyx in sage.matrix.matrix2.Matrix.right_kernel_matrix (build/cythonized/sage/matrix/matrix2.c:29656)()
4316 if M is None:
4317 try:
-> 4318 format, M = self._right_kernel_matrix(algorithm=algorithm, proof=proof)
4319 except AttributeError:
4320 pass
/usr/local/SageMath.94/local/lib/python3.9/site-packages/sage/matrix/matrix_integer_dense.pyx in sage.matrix.matrix_integer_dense.Matrix_integer_dense._right_kernel_matrix (build/cythonized/sage/matrix/matrix_integer_dense.cpp:22522)()
2694 proof = kwds.pop('proof', None)
2695 proof = get_proof_flag(proof, "linear_algebra")
-> 2696 K = self._rational_kernel_iml().transpose().saturation(proof=proof)
2697 format = 'computed-iml-int'
2698 else:
/usr/local/SageMath.94/local/lib/python3.9/site-packages/sage/matrix/matrix_integer_dense.pyx in sage.matrix.matrix_integer_dense.Matrix_integer_dense._rational_kernel_iml (build/cythonized/sage/matrix/matrix_integer_dense.cpp:32421)()
3882 time = verbose('computing null space of %s x %s matrix using IML'%(self._nrows, self._ncols))
3883 cdef mpz_t * m = fmpz_mat_to_mpz_array(self._matrix)
-> 3884 sig_on()
3885 dim = nullspaceMP(self._nrows, self._ncols, m, &mp_N)
3886 sig_off()
SignalError: Illegal instruction
----
`lscpu` output:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
Address sizes: 46 bits physical, 48 bits virtual
CPU(s): 40
On-line CPU(s) list: 0-39
Thread(s) per core: 2
Core(s) per socket: 10
Socket(s): 2
NUMA node(s): 2
Vendor ID: GenuineIntel
CPU family: 6
Model: 62
Model name: Intel(R) Xeon(R) CPU E5-2670 v2 @ 2.50GHz
Stepping: 4
CPU MHz: 2892.940
CPU max MHz: 3300.0000
CPU min MHz: 1200.0000
BogoMIPS: 4987.83
Virtualization: VT-x
L1d cache: 640 KiB
L1i cache: 640 KiB
L2 cache: 5 MiB
L3 cache: 50 MiB
NUMA node0 CPU(s): 0-9,20-29
NUMA node1 CPU(s): 10-19,30-39
Vulnerability Itlb multihit: KVM: Mitigation: Split huge pages
Vulnerability L1tf: Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown: Mitigation; PTI
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2: Mitigation; Full generic retpoline, IBPB conditional, IBRS_FW, STIBP conditional, RSB filling
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Not affected
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm cpuid_fault epb pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid fsgsbase smep erms xsaveopt dtherm ida arat pln pts md_clear flush_l1dMax AlekseyevTue, 31 Aug 2021 21:41:52 +0200https://ask.sagemath.org/question/58775/system eqs + eq with abs() then solve() kills the Kernelhttps://ask.sagemath.org/question/58202/system-eqs-eq-with-abs-then-solve-kills-the-kernel/ Hi
W10 ,SageMath 9.2
if I uncomment line 3 below, it kills the Kernel.
varL=var('a,b,c,d',domain='real')
eqL=[a == -d, b*c == 0, a*(b + c) == 0]
#eqL.append((abs(a)+abs(b)+abs(c))!=0)
show("so we need : \t ",eqL)
S=solve(eqL,varL)
show(S)
ortolljMon, 02 Aug 2021 10:28:54 +0200https://ask.sagemath.org/question/58202/Calculation with arbitrary precisionhttps://ask.sagemath.org/question/58144/calculation-with-arbitrary-precision/I know I can ask Sage to display the digits of Pi with arbitrary precision with `n(pi, digits= 202)` for example. Is it possible to ask it to perform an operation -- like a numerical integral -- to an arbitrary precision? That is, by specifying the number of significative digits.
I tried:
```
n(numerical_integral(exp(-1/x)/x, 0, 1 ),digits=200)
```
but that obviously produce the wrong answer.
I also know I can do:
```
integrate(e * exp(-1/x)/x,x, 0, 1 ).n(300)
```
but that integral seems to be computed symbolically.ApprenticeThu, 29 Jul 2021 02:21:07 +0200https://ask.sagemath.org/question/58144/Several charts at top create trouble with submanifoldshttps://ask.sagemath.org/question/57431/several-charts-at-top-create-trouble-with-submanifolds/My issue seems pretty trivial, however, I cannot find a way.
I create a manifold, with 2 frames/charts, and create transition_map between them.
Create a metric. I create then a submanifold, create `diff_map` to the first manifold,
and make an embedding. Then I try to get the `induced_metric`.
It works only if the `diff_map` is referenced to the first created frame/chart at top level.
In my example:
- top manifold with cartesian and cylindrical charts
- sub manifold is a cylinder. I cannot base it on the cylindrical top chart.
My purpose would be to have a top manifold series of charts
at top and natural embeddings of lower dimension manifolds.
Any idea?
My code:
E = Manifold(3, 'E', structure='Riemannian')
cartesian.<x,y,z> = E.chart()
cartesian_frame = cartesian.frame()
cylindrical.<r,ph,z> = E.chart(r'r:(0,+oo) ph:(0,2*pi):\phi z')
cylindrical_frame = cylindrical.frame()
cyl2cart = cylindrical.transition_map(cartesian , [r*cos(ph), r*sin(ph), z])
cart2cyl = cyl2cart.set_inverse(sqrt(x^2 + y^2), atan2(y, x), z)
ecc = E.coord_changes()
for cc in ecc:
display(ecc[cc].display())
g = E.metric()
g[cartesian_frame, 0, 0], g[cartesian_frame, 1, 1], g[cartesian_frame, 2, 2] = 1, 1, 1
display(g.display(cartesian))
display(g.display(cylindrical))
C2 = Manifold(2, 'C2', ambient=E, structure='Riemannian')
Cyl2.<ph,z> = C2.chart(r'ph:\phi z')
Cyl2_frame = Cyl2.frame()
if True: # True shows issue
E.set_default_frame(cylindrical_frame)
E.set_default_chart(cylindrical)
Cyl2tocylindrical = C2.diff_map(E, {(Cyl2, cylindrical): [1, ph, z]})
cylindricaltoCyl2 = E.diff_map(C2, {(cylindrical, Cyl2): [ph, z]})
C2.set_embedding(Cyl2tocylindrical)
else:
Cyl2tocartesian = C2.diff_map(E, {(Cyl2, cartesian): [cos(ph), sin(ph), z]})
cartesiantoCyl2 = E.diff_map(C2, {(cartesian, Cyl2): [arctan2(y, x), z]})
C2.set_embedding(Cyl2tocartesian)
C2g = C2.induced_metric() # never an error message here
display(C2g.display()) # exhibits the issueLPsFRThu, 03 Jun 2021 09:45:18 +0200https://ask.sagemath.org/question/57431/Bug? Polynomial variable name mattershttps://ask.sagemath.org/question/57796/bug-polynomial-variable-name-matters/The following calculation of an intersection of curves over `QQbar` raises an error within Singular on Sage v9.2.
P.<a, y, z> = ProjectiveSpace(QQbar, 2)
f = a^3 + z^3
C = Curve(f)
g = (a + y)^3 + z^3
D = Curve(g)
print(C.intersection_points(D))
It does work when replacing the variable name `a` by `x`.
I assume this is a bug but could not trace it down to the internals of `rational_points` and the Singular interface. The variables `b`and `d` work, whereas `c` raises a different error. Does anyone know more about that? Is it already fixed in the newer versions? Should I post this as a ticket on [https://trac.sagemath.org](https://trac.sagemath.org)?FabianGMon, 28 Jun 2021 13:13:57 +0200https://ask.sagemath.org/question/57796/Quotient of polynomial ring over integers not workinghttps://ask.sagemath.org/question/56734/quotient-of-polynomial-ring-over-integers-not-working/I have a problem. I want Sage to calculate in $\mathbb Z[x]/\langle4,2x,x^2\rangle$ but none of the relations are being calculated/recognized properly:
sage: R.<x> = ZZ[]
sage: I = R.ideal(4,2*x,x^2)
sage: S.<a> = R.quotient(I)
sage: a^2 # the output should be 0
a^2
sage: 2*a # the output should be 0
2*a
sage: S(2)+S(2) # the output should be 0
4
When I introduce a superfluous variable $y$ and consider $\mathbb Z[x,y]/\langle4,2x,x^2,y\rangle$ instead, which is practically the same ring (i.e. isomorphic), then it seems to work:
sage: R.<x,y> = ZZ[]
sage: I = R.ideal(4,2*x,x^2,y)
sage: S.<a,b> = R.quotient(I)
sage: a^2
0
sage: 2*a
0
sage: S(2)+S(2)
0
But now look at this:
sage: S(2)+S(3) # the output should be 1
5
How can I solve this problem?ThrashMon, 19 Apr 2021 22:33:39 +0200https://ask.sagemath.org/question/56734/Computing the factored multiplicative order of an extension field tries to solve an unnecessarily hard factoring problemhttps://ask.sagemath.org/question/56710/computing-the-factored-multiplicative-order-of-an-extension-field-tries-to-solve-an-unnecessarily-hard-factoring-problem/There seems to be a unnecessary performance problem with constructing large extension fields:
sage: p = 0x24000000000024000130e0000d7f70e4a803ca76f439266f443f9a5cda8a6c7be4a7a5fe8fadffd6a2a7e8c30006b9459ffffcd300000001
sage: GF(p^2)
This hangs trying to factor the 891-bit integer $p^2 - 1$, which is longer than the longest solved RSA Challenge number. (As it happens, the hard part of this factorization is a 675-bit integer which is still impractical.)
It is not unreasonable that constructing the extension field requires knowing the factorization of the multiplicative order. (You can get around this by constructing it with a specific modulus, but then many operations, e.g. taking roots, require this factorization anyway.)
However, we know that $p^2 - 1$ splits as $(p-1)(p+1)$, and factoring those may be much more feasible:
sage: factor(p-1)
2^32 * 3^4 * 17 * 67 * 293 * 349 * 1997 * 19556633 * 44179799701097 * 1461985442088199434216480729118540833655826472878315075486478169293801719414121837587283877
sage: factor(p+1)
2 * 313 * 751 * 2003 * 2671 * 738231097 * 55047696457335561580180364861378466840614260303507426009866606293225963076275651294902969015038913167956483928299
(this takes less than a second on my desktop).
In general, computing the multiplicative order of an extension field should take advantage of the factorization of $p^k - 1$ as a polynomial. There might also be other cases where we know the factorization by construction, and should be able to provide it.dairaSun, 18 Apr 2021 12:48:15 +0200https://ask.sagemath.org/question/56710/Finite Field Extensionhttps://ask.sagemath.org/question/56220/finite-field-extension/I am using SageMath version 9.2. I was trying the example in the documentation:
`sage: k = GF(2)`
`sage: k.extension(x^1000 + x^5 + x^4 + x^3 + 1, 'a')`
However, this gives the error: `UnboundLocalError: local variable 'E' referenced before assignment`
How do I fix this?
cathreyaThu, 18 Mar 2021 15:59:04 +0100https://ask.sagemath.org/question/56220/Plot "color_by_label" produces SQUARED number of lines in digraphhttps://ask.sagemath.org/question/56324/plot-color_by_label-produces-squared-number-of-lines-in-digraph/I bumped into this unusual behavior and am not sure how to fix it.
When I add `color_by_label` for plotting a digraph I get the correct
number SQUARED of lines appearing in the digraph. Is this an error
in SageMath or is there a workaround? All monochrome lines
do not work for my application.
This is my code sample:
stnc = 'ABCCCCDABCDABCDA'
g = DiGraph({}, loops=True, multiedges=True)
for a, b in [(stnc[i], stnc[i + 1]) for i in range(len(stnc) - 1)]:
g.add_edge(a, b, b)
sage: g.edges()
[('A', 'B', 'B'), ('A', 'B', 'B'), ('A', 'B', 'B'),
('B', 'C', 'C'), ('B', 'C', 'C'), ('B', 'C', 'C'),
('C', 'C', 'C'), ('C', 'C', 'C'), ('C', 'C', 'C'),
('C', 'D', 'D'), ('C', 'D', 'D'), ('C', 'D', 'D'),
('D', 'A', 'A'), ('D', 'A', 'A'), ('D', 'A', 'A')]
# This produces the correct number of lines SQUARED
g.plot(color_by_label=True, edge_style='solid', layout='circular').show(figsize=(8, 8))
# Correct number of lines but monochrome
g.plot(layout='circular').show(figsize=(8, 8))
![Incorrect edge multiplicity for multidigraph with color_by_label](/upfiles/16164608644236614.png)
Each edge should have multiplicity 3.
In the plot with color edges, each has multiplicity 9.
The plot with no colors has correct multiplicity 3 for each edge.JJTue, 23 Mar 2021 00:17:54 +0100https://ask.sagemath.org/question/56324/Function composition not workinghttps://ask.sagemath.org/question/56217/function-composition-not-working/I'm experiencing some strange behavior when composing two basic functions. My OS is Windows 10. Here is an example:
sage: r=var('r')
sage: s=var('s')
sage: f(r)=r**2
sage: g(r)=r**(1/2)
sage: f(g(r))
sqrt(r)
sage: f(g(s))
s
Whenever I evaluate the functions at the variable they were defined with (or even if just the outer function was defined with it), Sage returns the inner function as the result. This seems to happen only when the two functions are inverses of each other, since it behaves as expected with $f(r)=r^2$ and $g(r)=r^{1/3}$, returning $r^{2/3}$.
Is this a known issue? Is this somehow expected behavior? Thanks for any help.tarix29Thu, 18 Mar 2021 03:32:41 +0100https://ask.sagemath.org/question/56217/when I must declare f= or f(x,y)= ?https://ask.sagemath.org/question/55417/when-i-must-declare-f-or-fxy/HI
Sorry for this really basic SageMath question ;-( :
Does anyone know the reason why an error is generated when I uncomment the 3rd line?
and is it possible when a function was declared (f(x)=) object to return to (f=) object ?
and when I must declare f(x)= , or simply f= ?
despite the reading of [Some Common Issues with Functions](https://doc.sagemath.org/html/en/tutorial/tour_functions.html)
var('x')
SGN=(x+2)*(x+1)*(x-1)*(x+1)
#SGN(x)=(x+2)*(x+1)*(x-1)*(x+1)
show(SGN.parent())
f(x)=1/x*sin(x)
plt=plot(f,(x,-3,3),color='blue')
plt+=plot(SGN,(x,-3,3),color='black',linestyle='dashed')
plt+=plot(sgn(SGN),(x,-5,5),color='gray',linestyle='dashed')
show(plt,xmin=-2,xmax=2,ymin=-3,ymax=3, aspect_ratio=1)
show(numerical_integral(f,0,2)[0])
show(numerical_integral(-sgn(SGN)*f,0,1)[0]+numerical_integral(sgn(SGN)*f,1,2)[0])ortolljFri, 22 Jan 2021 11:32:00 +0100https://ask.sagemath.org/question/55417/How do I understand the result of symbolic integralshttps://ask.sagemath.org/question/7574/how-do-i-understand-the-result-of-symbolic-integrals/So now I know how to integrate, but when I type in
sage: deriv=diff((exp(x)-1)/x,x); deriv
e^x/x - (e^x - 1)/x^2
sage: deriv.integrate(x)
-1/x + Ei(x) - gamma(-1, -x)
why don't I get back `(exp(x)-1)/x +C `?
Philipp SchneiderWed, 18 Aug 2010 20:04:12 +0200https://ask.sagemath.org/question/7574/Possible inconsistency in symbolic limitshttps://ask.sagemath.org/question/55370/possible-inconsistency-in-symbolic-limits/I was trying to manipulate some symbolic expressions and got an unexpected error.
Here is a minimal example,
u=integrate(x**3/(exp(x)-1),(x,0,oo))
The expression is quite messy, but the result is known. When I try to use any simplification routine, like
u.simplify()
sage displays the error message
RuntimeError: ECL says: Error executing code in Maxima: limit: direction must be either 'plus' or 'minus'; found: _SAGE_VAR_minus
As far I understood, the expression is defining lateral limits by symbolic variables, while maxima handle such limits as strings. If it is the case there is an internal conflict here. Is it the case?cav_rtWed, 20 Jan 2021 02:58:40 +0100https://ask.sagemath.org/question/55370/inverse image under ring homomorphismhttps://ask.sagemath.org/question/55099/inverse-image-under-ring-homomorphism/Hi there!
Just starting to learn Sage and can't get why both `inverse_image` calls
below give an error saying the given element does not have a preimage,
while `y^2` clearly has `xbar` as preimage.
Referring to the generators of `R1` and `R2` explicitly doesn't help either.
sage: R.<x, y> = QQ[]
sage: R1 = R.quotient(R.ideal(y^2 - x^3))
sage: R2 = R.quotient(R.ideal(x))
sage: h = R1.hom([y^2, y^3], R2)
sage: h
Ring morphism:
From: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (-x^3 + y^2)
To: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x)
Defn: xbar |--> y^2
ybar |--> y^3
sage: h.inverse_image(y)
Traceback (most recent call last)
...
ValueError: element y does not have preimage
sage: h.inverse_image(y^2)
Traceback (most recent call last)
...
ValueError: element y^2 does not have preimage
Thanks!KarinaMon, 04 Jan 2021 15:12:56 +0100https://ask.sagemath.org/question/55099/tensor_product of matrices over cyclotomic fieldhttps://ask.sagemath.org/question/54762/tensor_product-of-matrices-over-cyclotomic-field/Beginner question: I have created some matrices over a cyclotomic field and attempted to compute some of their tensor products:
N = 3
k.<w> = CyclotomicField(N)
Z = diagonal_matrix(k,N,[w^j for j in range(0,N)])
X = matrix(k,N,N,[1 if (i%N - floor(i/N)) % N == N-1 else 0 for i in range(0,N*N)])
I = identity_matrix(k,N)
I.tensor_product(X)
X.tensor_product(I)
Z.tensor_product(I)
Z.tensor_product(X)
#I.tensor_product(Z)
#X.tensor_product(Z)
If I uncomment either of the last two lines I get
> AttributeError: 'sage.matrix.matrix_generic_sparse.Matrix_generic_sparse' object has no attribute '_rational_matrix'
It seems my code is working when both matrices in the tensor product are rational or when self is non-rational, but not when self is rational and the argument is non-rational. Should I be somehow instructing sagemath to regard self as a matrix over the cyclotomic field?Will OrrickSat, 19 Dec 2020 20:38:38 +0100https://ask.sagemath.org/question/54762/Assumption seems to break integrate(); is this a bug?https://ask.sagemath.org/question/52382/assumption-seems-to-break-integrate-is-this-a-bug/Consider the following Sage code (tested using Sage 8.6):
var('t')
var('a')
t.integrate(t, 0, a) # \int_{0}^{a} t dt
Output (as expected):
t
a
1/2*a^2
Next:
t.integrate(t, 0, 4*a - a^2) # 4*a - a^2 could be positive, negative, non-real(?)
Output (again, no problem):
1/2*a^4 - 4*a^3 + 8*a^2
Now suppose we give Sage a little more information. The following assumptions should guarantee that we're integrating over a real interval, and that the second (or "top") endpoint is strictly greater than the first ("bottom") endpoint. (Though as we have seen, Sage does not really need this information.)
assume(a, 'real')
assume(a > 1)
assume(a < 3) # now 0 < a < 4, so 4*a - a^2 > 0
t.integrate(t, 0, 4*a - a^2) # hangs, eventually produces RuntimeError
So, `.integrate()` succeeds when nothing is known about the endpoint, but then fails when given more information.
**My Question: Is this desired/expected behavior, or would it be considered a bug?**
Personally, I found it surprising: I expected that, if a command worked with no assumptions, then it should still work after adding assumptions (consistent assumptions that only narrow the scope of the problem).
*What follows is purely my own speculation; feel free to ignore.*
I also get a similar kind of problem if I do the following:
forget()
var('t'); var('a');
assume(a, 'real')
assume(a > 1)
assume(a < 3)
bool(4*a - a^2 > 0) # hangs, RuntimeError
It seems to me that $1 < a < 3$ implies $0 < a < 4$, which implies that $-a^2 + 4a > 0$. (The graph of the quadratic is a downward-opening parabola, with roots at $0$ and $4$.) I am not surprised that Sage has trouble constructing this argument, so I am not surprised that the `bool()` command hangs. But unfortunately this also seems to break `.integrate()`, which was working otherwise.
So, I speculate that maybe the `.integrate()` method, when faced with an integral whose endpoints are known to be real, first tries to figure out which endpoint is greater? But sometimes this process hangs, so the `.integrate()` process never terminates?
In our case, I think Sage assumes by default that `a` is complex-valued(?), and then it has no problem with the integral. So it seems like it should still work when `a` is in the real interval $(1, 3)$, which after all is a subset of $\mathbb{C}$.
By the way, the following works just fine:
forget()
var('t'); var('a');
assume(4*a - a^2 > 0)
print(bool(4*a - a^2 > 0))
t.integrate(t, 0, 4*a - a^2)
Or, this also works:
t.integrate(t, 0, 2*a - a^2, algorithm='sympy')
Asked also at [Math Stackexchange](https://math.stackexchange.com/questions/3739105/assumption-seems-to-break-sages-integrate-function-is-this-a-bug), but did not receive an answer there. Apologies if this kind of cross-posting is frowned upon.mathmandanThu, 09 Jul 2020 03:26:26 +0200https://ask.sagemath.org/question/52382/minimize_constrained works for f(x,y)=x+y but not for f(x,y)=xhttps://ask.sagemath.org/question/54720/minimize_constrained-works-for-fxyxy-but-not-for-fxyx/Hi, need help to understand why `minimize_constrained`
works for `f(x, y) = x + y` but does not work for `f(x, y) = x`.
Example:
var('x, y')
f(x, y) = x + y
c(x, y) = 1 - x^2 - y^2
minimize_constrained(f(x, y), [c(x, y)], [0, 0])gpiresThu, 17 Dec 2020 01:53:54 +0100https://ask.sagemath.org/question/54720/Generators of simplicial homologyhttps://ask.sagemath.org/question/54070/generators-of-simplicial-homology/ I have this code to compute the homology of a simplicial complex
S = SimplicialComplex([[5, 2], [5, 2, 1], [5, 0], [5, 1], [4, 3], [4, 3, 0], [4, 2], [4, 0], [3, 0], [3, 1], [2, 1],])
S.homology(generators = True)
The output only consists of the homology, and does not contain the generators. Am I missing something?
springfieldgionThu, 29 Oct 2020 12:49:00 +0100https://ask.sagemath.org/question/54070/Crash with polynomial over "Givaro" finite fieldhttps://ask.sagemath.org/question/53696/crash-with-polynomial-over-givaro-finite-field/I would like to solve a system of equations
in a finite field of prime order $p$
(illustrated below with $p = 229$).
The system consists in four equations and has four unknowns
$a_0$, $a_1$, $a_2$, $a_3$.
It depends on parameters $\alpha_i$, $b_i$, all in $F(p)$,
for $i = 1, 2, 3, 4$.
The four equations are
$$a_0 + a_1 \alpha_1 + a_2 \alpha_1^2 + a_3 \alpha_1^3 = b_1$$
$$a_0 + a_1 \alpha_2 + a_2 \alpha_2^2 + a_3 \alpha_2^3 = b_2$$
$$a_0 + a_1 \alpha_3 + a_2 \alpha_3^2 + a_3 \alpha_3^3 = b_3$$
$$a_0 + a_1 \alpha_4 + a_2 \alpha_4^2 + a_3 \alpha_4^3 = b_4$$
To do this I have tried with the following examples:
pm = 229
bp = 229
F.<x> = GF(pm, impl='givaro')
R.<a0, a1, a2, a3> = PolynomialRing(F)
def NP(a):
return F(ZZ(a).digits(bp)) # integer to polynomial
eqns = [a0 + a1*NP(2) + a2*NP(2)^2 + a3*NP(2)^3 - NP(78),
a0 + a1*NP(3) + a2*NP(3)^2 + a3*NP(3)^3 - NP(136),
a0 + a1*NP(4) + a2*NP(4)^2 + a3*NP(4)^3 - NP(179),
a0 + a1*NP(5) + a2*NP(5)^2 + a3*NP(5)^3 - NP(166)]
A = matrix(F, [[eqn.coefficient(b) for b in R.gens()] for eqn in eqns])
b = vector(F, [-eqn.constant_coefficient() for eqn in eqns])
X = A.solve_right(b)
print(X)
But it shows erros:
Unhandled SIGSEGV: A segmentation fault occurred.
This probably occurred because a *compiled* module has a bug
in it and is not properly wrapped with sig_on(), sig_off().
Python will now terminate.
------------------------------------------------------------------------
/usr/share/sagemath/bin/sage-python: line 2: 7655 Segmentation fault (core dumped) sage -python "$@"
How can I fix this?MKSFri, 02 Oct 2020 01:48:21 +0200https://ask.sagemath.org/question/53696/Bug with newton polygons of Puiseux series in 9.1?https://ask.sagemath.org/question/53628/bug-with-newton-polygons-of-puiseux-series-in-91/I've been playing with Puiseux series and noticed that zero coefficients are not being assigned the correct valuation of infinity, so that the Newton polygon is not always correct. A minimal example follows: the two newton polygons should be the same, but they are not. The polygon for f2 is correct, while that of f1 is in error.
R.<x> = PuiseuxSeriesRing(QQ)
S.<y> = PolynomialRing(R)
f1 = y^2+x
f2 = y^2+x*y+x
X1=f1.newton_polygon().plot()
X2=f2.newton_polygon().plot()
show(X1)
show(X2)
If you do the same thing with Laurent series as opposed to Puiseux series, there is no problem and the polygons are equal (as expected):
R.<x> = LaurentSeriesRing(QQ)
S.<y> = PolynomialRing(R)
f1 = y^2+x
f2 = y^2+x*y+x
X1=f1.newton_polygon().plot()
X2=f2.newton_polygon().plot()
show(X1)
show(X2)
Similarly if you work over a p-adic field, there is no problem:
K=pAdicField(2)
S.<y> = PolynomialRing(K)
f1 = y^2+2
f2 = y^2+2*y+2
X1=f1.newton_polygon().plot()
X2=f2.newton_polygon().plot()
show(X1)
show(X2)
So this does seem to be a problem specific to Puiseux series. I'm not sure how to post a bug report, so I'm documenting this here in the hope that someone can help. Thanks!cfrancSun, 27 Sep 2020 23:32:57 +0200https://ask.sagemath.org/question/53628/Sage symbolic math simplification errorhttps://ask.sagemath.org/question/53345/sage-symbolic-math-simplification-error/In sagemath version 9.1, the code
product(1-q^x, x, 1, N)
returned
-(-1)^N*product(q^x - 1, x, 1, N)
while the correct result ought to be
(-1)^N*product(q^x - 1, x, 1, N)
What went wrong? Where did this sign change come from?ShoutOutAndCalculateMon, 07 Sep 2020 03:21:09 +0200https://ask.sagemath.org/question/53345/