# 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.rhs(),sltns.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 .rhs(). Isn't sltns the way to select, for example, [d==4] in [a==2, b==3, d==4], while sltns and sltns 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?

edit retag close merge delete

Sort by » oldest newest most voted

There were a few issues with your code.

1. sltns is a list containing the list of solutions. So, you need to access sltns before accessing each piece of a solution.
2. You cannot use the name c for the variable in the symbolic solution and in the loop.
3. You need to substitute the c value within the loop into the solution.
4. There is no solution when c=1.

Here is the corrected code.

var('n u c')
sltns=solve([n + u==0, n + c*u - 1==0], n, u)
print sltns
L = [0, 1/4, 1/2, 3/4, 5/4, 6/4, 7/4, 2]
for c1 in L:
print (c1,sltns.rhs().subs(c==c1),sltns.rhs().subs(c==c1) )


To answer your second question, you can collect the information into a list of the rows and then convert to a matrix.

var('n u c')
sltns=solve([n + u==0, n + c*u - 1==0], n, u)
print sltns
L = [0, 1/4, 1/2, 3/4, 5/4, 6/4, 7/4, 2]
rows=[]
for c1 in L:
print (c1,sltns.rhs().subs(c==c1),sltns.rhs().subs(c==c1) )
rows.append([c1,sltns.rhs().subs(c==c1),sltns.rhs().subs(c==c1)] )
m=matrix(rows)
m

more

I need to some more karma myself to be able to upvote your answer (I'll upvote after using the site some more and getting more karma). BTW, to clarify, if there were three variables solved for, I would need to select the third one by writing sltns, yes?