ASKSAGE: Sage Q&A Forum - Latest question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Thu, 06 Jun 2019 19:50:09 -0500How to define multiple objects with a for loop?http://ask.sagemath.org/question/46844/how-to-define-multiple-objects-with-a-for-loop/ While this question can be answered in greater generality, I'm specifically writing a program in which I need to systematically define and label a bunch of differential forms.
Suppose I have the set up
M = manifold(2, 'M')
U = M.open_subset('U')
c_xy.<x,y> = U.chart()
eU = c_xy.frame()
Now I want to have a bunch of differential forms indexed by 2 numbers (as they will be going into a matrix).
Instead of writing them all out by hand as
a_00 = M.diff_form(1, name='a_00')
a_01 = M.diff_form(1, name='a_01')
...
a_33 = M.diff_form(1, name='a_33')
Is there any way I can write a for loop to build these for me? I've seen a similar question asked here:
https://ask.sagemath.org/question/7925/a-list-of-symbolic-variables/
but I'm not sure how to extend to the 2-index case. Also, the linked example works for symbols, but I don't know if this can be made to work for defining a list of objects like differential forms. sum8tionThu, 06 Jun 2019 19:50:09 -0500http://ask.sagemath.org/question/46844/how to append to a symbolic expression in a loop?http://ask.sagemath.org/question/46377/how-to-append-to-a-symbolic-expression-in-a-loop/This must be super basic, but i don't get how to do the classic
for i in list:
expression = expression + i
symbolically. I want to add new terms to the expression, and the "==" notation does not mash well with that.
An .append() method would make sense, but i was not able to find one.stockh0lmSat, 27 Apr 2019 15:18:13 -0500http://ask.sagemath.org/question/46377/How to skip a single loop iterationhttp://ask.sagemath.org/question/42837/how-to-skip-a-single-loop-iteration/I have the following code:
for k in range(9):
if k != 3:
print(k)
else:
print(20)
# i want to skip the next iteration
So I want to get: 0,1,2,20,5,6,7,8, here I skip the fourth iteration.
I already try to use the command next(), but it doesn't give what I want
MarioMThu, 05 Jul 2018 19:30:36 -0500http://ask.sagemath.org/question/42837/Is it possible to speed up loop iteration in Sage?http://ask.sagemath.org/question/41375/is-it-possible-to-speed-up-loop-iteration-in-sage/I have a sage code that looks like this:
uni = {}
end = (l[idx]^(e[idx] - 1)) * (l[idx] + 1) # where end in my case is about 2013265922 but can also be much larger
for count in range(0, end):
i = randint(1, 303325737249669131)
if i in uni:
uni[i] += 1
else:
uni[i] = 1
So basically, I want to create very large number of random integers in the given range, check whether the number was already in the dictionary, if yes increment its count, if not initialize it to 1. But, this takes such a long time that it doesn't finish in a reasonable time. Is there any way to speed up this kind of loops in Sage (or Python)?ninhoSat, 03 Mar 2018 05:10:30 -0600http://ask.sagemath.org/question/41375/Not evaluating the coordinateshttp://ask.sagemath.org/question/36621/not-evaluating-the-coordinates/ I have the following code
D(f,m)=16*f^4*m^4 + (-144*f^10 + 432*f^9 - 472*f^8 - 1040*f^7 + 1672*f^6 + 784*f^5 - 3256*f^4 - 2896*f^3 - 392*f^2 + 128*f - 64)*m^2 + (36*f^14 - 468*f^13 + 3321*f^12 + 1224*f^11 - 8982*f^10 + 10332*f^9 + 29583*f^8 + 144*f^7 - 21024*f^6 - 4572*f^5 + 7047*f^4 + 3816*f^3 + 306*f^2 - 108*f + 81)
[(f,m) for m in [-10..10] for f in [-10..10] if D==0]
where I want to find all values of `(f,m)` that gives `D=0`. I have checked using Pari that one of the point is `(-1,0)`, and also, `(1,2)`. But when i run the coding it gives empty set. ShaWed, 15 Feb 2017 03:04:35 -0600http://ask.sagemath.org/question/36621/Problem with my for-loophttp://ask.sagemath.org/question/34280/problem-with-my-for-loop/
Does someone know how to get answer to this ?
list = [x for x in range (100) if (x + 0.75) == 20]
I was experimenting with Sage when computer says that there isn´t possible answer [] to this elementary maths problem .
There is any problem with using decimals number in a list?
I also try doing this : but it still doesn´t working
list = [float(x) for x in range (100) if (x + 0.75) == 20]
Thank you so much , Excuse my bad English! :))ImproveMESun, 31 Jul 2016 08:48:47 -0500http://ask.sagemath.org/question/34280/Naming variables in a loophttp://ask.sagemath.org/question/31794/naming-variables-in-a-loop/ I have this problem:
Lets say i have an matrix A and use A.gram_schmidt() on it. then i get a matrix B whose rows are orthogonal. So what do i do now if i want use the vectors of the rows. How can i make them to variables practical? I tried this:
O, t = A.gram_schmidt()
for i in range(n):
wi = O.row(i)
But clearly this doesnt work, because sage doesnt identiy the "i" in "wi"... bruno171092Wed, 23 Dec 2015 07:27:45 -0600http://ask.sagemath.org/question/31794/For loop strange order of executionhttp://ask.sagemath.org/question/31715/for-loop-strange-order-of-execution/On cloud.sagemath.com server I have run this code:
for k in [0..(len(G)-1)]:
G[k][0],G[k][1]
graphics_array([G[k][2].plot(color_by_label={'p':'black', 'r':'blue'}),G[k][3].plot(color_by_label={'p':'black', 'r':'blue'}),G[k][4].plot(color_by_label={'p':'black', 'r':'blue'})])
and I obtain correct effect, that is two elements ( which is text) G[k][0],G[k][1] and then plot for 3 additional elements in graphics array 1x3.
On my own instance of sagemath ( ver. 6.8) there is complete different!
The same code produces first list of 36 elements of G[k][0],G[k][1] and thet 36 plots.
Is this normal?
kakazSun, 20 Dec 2015 13:41:34 -0600http://ask.sagemath.org/question/31715/Error when using 'for in range()' but not ' for in [..]'http://ask.sagemath.org/question/30733/error-when-using-for-in-range-but-not-for-in/I've just started using SageMath today, and I've been pleasantly surprised at how good it is. I've been working through tutorials and playing around with plotting functions without any major problems until I wrote a series of nested for-loops using range values.
I'm getting the error 'ValueError("plot start point and end point must be different")', but only when the outer loop uses 'for r1 in range(3,6)', not when I do exactly the same thing using 'for r1 in [3..5]'.
Am I doing something newbie-naive here, or is this a bug?
Here's the full script:
t = var('t')
g = Graphics()
for r1 in [3..5]: # This works as expected
#for r1 in range(3,6): # This produces error: File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/plot/misc.py", line 136, in setup_for_eval_on_grid raise ValueError("plot start point and end point must be different")
g = g + circle((0, 0), r1, rgbcolor=(0.5,0.5,0.5))
for r2 in range(1, r1):
f = floor((r1 + r2) / 2)
for d in range(1, f):
print "r1 =",r1, " r2 =", r2, " d =",d; # debug msg
g = g + parametric_plot(((r1 - r2) * cos(t) + d * cos((r1 - r2) * t / r2), (r1 - r2) * sin(t) - d * sin((r1 - r2) * t / r2)), (t, 0, r2 / r1 * (pi ^ pi)), rgbcolor=(r2/r1, d / f, 0.5))
g.show()PhilstixSun, 15 Nov 2015 00:32:19 -0600http://ask.sagemath.org/question/30733/creating list n many timeshttp://ask.sagemath.org/question/29935/creating-list-n-many-times/ How to define n many empty lists where n is the number of vertices of the given arbitrary graph.
Thanks in advance.GA316Mon, 12 Oct 2015 08:45:30 -0500http://ask.sagemath.org/question/29935/numerical solutions from a for-loop solve()http://ask.sagemath.org/question/26661/numerical-solutions-from-a-for-loop-solve/I am trying to extract a list of 3-tuples which solve a system of equations. For the test I am using a simply equation whose solutions go from negative to positive around one, so
n, u = var('n, u')
sltns=solve([n + u==0, n + c*u - 1==0], n, u)
L = [0, 1/4, 1/2, 3/4, 1, 5/4, 6/4, 7/4, 2]
for c in L:
print (c,sltns[0].rhs(),sltns[1].rhs())
does not work.
What I am trying to get is, for example, if c = 1/2, then
(1/2, 2, -2]
because if c = 1/2 then n==2 and u==-2. And so on for all the elements of the list.
()
()
...
()
If I omit defining sltns, but use the solve() directly, I get out of range errors when for some c, u goes from positive to negative or vice versa for n, and I use [0].rhs(). Isn't sltns[2] the way to select, for example, [d==4] in [a==2, b==3, d==4], while sltns[0] and sltns[1] select the first two? Is it limited to some range positive or negative?
My question is:
1. What is the correct way to code the calculation above?
2. How would I alternatively code the loop if I needed the () s to be tuples in a matrix [(),(), ..., ()] for further calculations or plotting?gottfriedMon, 27 Apr 2015 21:45:24 -0500http://ask.sagemath.org/question/26661/Define differential form in n variableshttp://ask.sagemath.org/question/10917/define-differential-form-in-n-variables/I'd like to define a differential form in n variables (where n is defined beforehand, and I'd like for it to be able to be arbitrarily big. For this reason I'd like to write a code for general n). My first idea is to write something of the sort:
n=var('n');
n=3;
x = list(var('x_%d' % i) for i in (1..n));
U = CoordinatePatch(x);
F = DifferentialForms(U);
w = DifferentialForm(F,2);
[w[i,2]=3 for i in range(0,n-1)]
The value w[i,2]=3 is obviously arbitrary. I don't know why the code doesn't work, it says that there's a syntax error with w[i,2]=3.rfauffarWed, 15 Jan 2014 11:28:42 -0600http://ask.sagemath.org/question/10917/[x^14+x^i+x^j with (i,j) in (13,13) where j<i]http://ask.sagemath.org/question/10817/x14xixj-with-ij-in-1313-where-ji/How can I do it?
![image description](http://imageshack.us/a/img401/9886/uftf.jpg)
to get:
[x^14, x^14 + 1, x^14 + x + 1, x^14 + x^2 + x, x^14 + x^2 + 1,...kpasaxSun, 08 Dec 2013 15:46:56 -0600http://ask.sagemath.org/question/10817/computation limtations in Sage cloudhttp://ask.sagemath.org/question/10738/computation-limtations-in-sage-cloud/Hi everybody
I'm working on an exercise in technical chemistry and try to find concentration progresses by numerical calculation. Note that im pretty new to Sage and Python.
The problem i encounter is that as soon as i want to use more than 20 iterations, Sage cloud doesn't finish. I was able to have more iterations when my loop was smaller.
Is there a limitation on the computional power, that is provided by Sage cloud?
If you think the problem is with my code, I will post it.
Greetings, marvmarvFri, 15 Nov 2013 23:26:51 -0600http://ask.sagemath.org/question/10738/Difference between sum and for loophttp://ask.sagemath.org/question/10669/difference-between-sum-and-for-loop/Hi,
I'm currently using sage to calculate some double sums over two variables, where s runs from 1 to t-1, and t runs from 2 to 2*x+2*n+1. I initially used two nested for loops inside the following function:
def qentr(i,j,k,x,n):
s,t,sm = var('s,t,sm')
sm = 0
for t in range(2,2*x+2*n+2):
for s in range(1,t):
sm = sm + h(i,s,k,x,n)*h(j,t,k,x,n) - h(j,s,k,x,n)*h(i,t,k,x,n)
return sm
where i, j, k, x, n are all nonnegative integers. This gives me the correct values for what I am enumerating, for instance qentr(1,3,3,1,2) = 96, which is right. For some reason when I replace these for loops with two nested sums, say,
sum(sum(h(i,s,k,x,n)*h(j,t,k,x,n)-h(i,t,k,x,n)*h(j,s,k,x,n),s,1,t-1),t,2,2*x+2*n+1)
this no longer gives me the correct values. If I replace the two nested loops with this sum I get qentr(1,3,3,1,2)=196....
I wanted to replace the loops with sum in order to return an expression in x, the only way I can think to do this is with sum but this does not yield the right expression. Does anyone know why this happens? Does anyone know an alternative way I can get the function qentr() to return a polynomial in x?
The function h from above is the following:
def h(i,j,k,x,n):
r = var('r')
return binomial(j-1,i-1)-2*sum(binomial(r+i-k,i-k)*binomial(j-i-r+k-2,k-2),r,x+n+(k+1)/2+1-i,j-i)
Cheers!tommytricksMon, 28 Oct 2013 07:04:05 -0500http://ask.sagemath.org/question/10669/Plot with prime numbershttp://ask.sagemath.org/question/10519/plot-with-prime-numbers/I am trying to create a visualization of how common it is for a number to be prime. I am fairly new with the program and was hoping to get some assistant with any veteran users. My code I wrote is:
def com_primes(k):
prime_list = []
for n in range(1,k+1):
for m in range(1,n+1):
if Integer(n)/Integer(n) & Integer(n)/1 in ZZ:
if is_prime(m):
prime_list.append((n,m))
return point(prime_divisor_list)
but the code is obviously wrong. If anyone could help me, that would be much appreciated.hee1Fri, 06 Sep 2013 10:39:58 -0500http://ask.sagemath.org/question/10519/Tuples or for loopshttp://ask.sagemath.org/question/10418/tuples-or-for-loops/Hi everybody, I would like to compute the $L$-function of an elliptic curve of the form $$y^2=x^3-d^2x$$
for multiple values of $d$ at $s=1$. I was hoping to use an $n$-tuple
d=(1,3,5,7,...,n)
with the hope that I could then do
E=EllipticCurve([0,0,0,-(d^2),0])
L = E.lseries().dokchitser()
L(1)
such that at every stage the data would be in a vector/$n$-tuple form, but this is not possible. Does anyone know how I can make this method work? With a for-loop perhaps? Thanks in advance for your help!BlackadderMon, 05 Aug 2013 23:56:01 -0500http://ask.sagemath.org/question/10418/How to compute an iterated product in Sagehttp://ask.sagemath.org/question/10219/how-to-compute-an-iterated-product-in-sage/I am wondering about how to define a function `f(n, k, i)` that will take inputs `n`, `k`, `i` and give me the following product:
$$
\prod_{\ell = 1}^i {n + k - \ell \choose k}
$$
So for $i = 2$, this would look like ${n + k - 1 \choose k}\cdot {n + k - 2 \choose k}$. Would I use a for loop to iteratively add to the product until all `i` terms were accounted for?JoshIzzardMon, 10 Jun 2013 10:58:24 -0500http://ask.sagemath.org/question/10219/Problem getting indices to sync uphttp://ask.sagemath.org/question/10170/problem-getting-indices-to-sync-up/I'm not sure what is wrong with the following code:
# given a prime p, return all A_n representations of dimension = p^2
def rankrep(p):
bound = p**2
A = lambda i: WeylCharacterRing("A{0}".format(i), style = "coroots")
deg = []
for i in xrange(bound):
deg.append([])
fw = A(i+1).fundamental_weights()
temp = A(i+1)
for j in range(len(fw)):
deg[i].append(temp(fw[j]).degree())
return deg
But when I run it, it is unable to return anything, and tells me `Keyval Error 0`. Should I not be using `append` here?
I eventually hope to insert some `if` trees testing whether a given `temp(fw[j].degree() == p**2`, but I'm not sure how to pull those indices either. Any help would be greatly appreciated. Regards. JoshIzzardThu, 30 May 2013 07:37:25 -0500http://ask.sagemath.org/question/10170/How to find instances where $d(a,b) = p^2$ for $p$ a primehttp://ask.sagemath.org/question/10140/how-to-find-instances-where-dab-p2-for-p-a-prime/Suppose I have a dimension formula (for a Lie algebra representation) given by
$\mathrm{dim}_{a,b} = {(a+1)(b+1)(a+b+2) \over 2}$. I now would like to find pairs $(a,b)$ where $\dim_{a,b} = p^2$ for $p$ a prime? What are some techniques for accomplishing this? Should I first filter out a list of primes using `isprime` and then check possible pairs $(a,b)$ for each prime $p < N$, say $1000$.
JoshIzzardThu, 23 May 2013 07:12:39 -0500http://ask.sagemath.org/question/10140/How to define multiple WeylCharacterRings at one timehttp://ask.sagemath.org/question/10131/how-to-define-multiple-weylcharacterrings-at-one-time/I am trying to use a script like the one below (to use a simplistic version)
for i in [1..4]:
B"i" = WeylCharacterRing("Bi")
to define multiple Weyl character rings at one time. I then am hoping to go through, and compute the degrees of the representation corresponding to the weight (1,1,1,...,1) depending on which B$i$ I am considering i.e., for $B4$ I would want to calculate
B4(1,1,1,1).degree()
(its $126$). How can I go about automating this in some way? Any tips or reference materials?
Thanks for your time. JoshIzzardFri, 17 May 2013 06:32:51 -0500http://ask.sagemath.org/question/10131/Multiple loops in an animation?http://ask.sagemath.org/question/9205/multiple-loops-in-an-animation/I want to use two loops to produce an animation of some gridlines changing gradient.
Essentially making all these lines:
t=var('t')
p1=Graphics()
p2=Graphics()
for i in range(-5,5,1):
p1 +=parametric_plot((t,i),(t,-5,5),color="red")
p2 +=parametric_plot((i,t),(t,-5,5),color="blue")
show(p1+p2)
Move like these lines all at once:
t=var('t')
p1=Graphics()
p2=Graphics()
v = []
for a in srange(-5,5,1):
p1 =parametric_plot((t,t*a),(t,-5,5),color="red")
p2 =parametric_plot((t*a,t),(t,-5,5),color="blue")
v.append(p1+p2)
j = animate (v, xmin=-2,ymin=-2,xmax=2,ymax=2,figsize=[2,2])
j.show()
How can I combine these two into one animation? Insaneg33kSat, 04 Aug 2012 05:53:38 -0500http://ask.sagemath.org/question/9205/Add graphs produced by a for loop?http://ask.sagemath.org/question/9045/add-graphs-produced-by-a-for-loop/How can I plot all my graphs that i produce from a for loop on top of each other? I have this:
for i in range(-3,3,1):
p1 = parametric_plot((t,i),(t,-5,5),color="red")
p2 = parametric_plot((i,t),(t,-5,5),color="gray")
show(p1+p2)
I just get all the graphs one after the other. Insaneg33kFri, 08 Jun 2012 05:01:40 -0500http://ask.sagemath.org/question/9045/plotting multiple functions from a for loophttp://ask.sagemath.org/question/9024/plotting-multiple-functions-from-a-for-loop/Here I link to a worksheet with which I'm having the darnedest trouble...
[PlotTest](http://www.sagenb.org/home/pub/4787/)
The code in the worksheet makes it easy to plot many similar plots, and this is a pretty organized way to do it. I got it to work once, but I changed something and made too many changes afterward to get it working again to undo back to my original code.
The problem is in the third cell, obviously. I want to assign to '**a**' "*plot all of the functions in the list **funclist***." I realize that they aren't functions, really (they aren't assigned names such as f0,f1,f2, etc), but I'll try to solve that another day. But anyway, how can I set this loop up to add all of these plots and dump them into an object? I need to be able to input '**a**' and get a plot containing all of these.
As is evident from the worksheet, I can't use the operator += (though I swear I did the first time).
I would rather not to do it like this:
a = plotlist[0]
for i in range(1,len(plotlist)):
a += plotlist[i]
Because that requires that I spread out the definition of '**a**' and has an unnecessary amount of code. However, that seems to be the easiest way to do it.
But I would like to be able to do it in two lines of code --- for i in plotlist, add all these plots to this object. Or three lines, if I have to initialize '**a**' beforehand (give it a type or whatever.)daniel.e2718Fri, 01 Jun 2012 18:25:51 -0500http://ask.sagemath.org/question/9024/multiple parametric_plot's with for loophttp://ask.sagemath.org/question/8988/multiple-parametric_plots-with-for-loop/I'm studying differential geometry of curves and surfaces, and I have a question regarding multiple plots on one graphics, that is i want to plot multiple lines on one plot in for loop, but when I try to do that it shows only the last plot...
a,b,v,u = var('a b v u'); rectangular=(a,b,v);
z=0;
for i in range(81):
z=i*pi/20;z
pt=plot3d(z*v,(v,0,5),(a,0,5),(b,0,5),transformation=rectangular,plot_points=80,color="blue")
show(pt)markisaSun, 20 May 2012 23:47:33 -0500http://ask.sagemath.org/question/8988/Plotting successive 3D plots in a for loop (only the last one can be plotted!)http://ask.sagemath.org/question/7873/plotting-successive-3d-plots-in-a-for-loop-only-the-last-one-can-be-plotted/Hi,
I have another problem with plotting multiple 3D plots.
When I execute the following two cells in the notebook interface:
Cell 1: (Definition of function that generates parametrized plots)
def plotPerceFL1 (aalpha):
p1_11 = plot3d(Fp1_11(alpha=aalpha),(x,0,1),(y,0,1),color="red")
p1_12 = plot3d(Fp1_12(alpha=aalpha),(x,0,1),(y,0,1),color="gray")
return p1_11+p1_12
Cel 2: (Plotting successive plots for different values of aalpha)
for a in srange(-1,1,step=0.25):
grr=plotPerceFL1(a)
grr.show()
I can see the loop running (if I print a, for example) but nothing is plotted until the end of the loop, then only the last graphic is shown.
Is there any trick to force Sage to successively plotting all graphics (and, preferably, to keep them in the screen one below the other)?
Thanks in advance for your help.
MuratmyildiWed, 26 Jan 2011 05:11:14 -0600http://ask.sagemath.org/question/7873/