convert string to sage expression

233 views
Skip to first unread message

geir.e...@gmail.com

unread,
Aug 29, 2008, 7:00:51 PM8/29/08
to sage-support
Hi,
I want to construct a set of equations using strings. For example:

for i in range(0,10):
eq1="eq=x^"+str(i)+"-"+str(i)

Is there a way to convert the string eq1 to a sage expression that can
be used
by the sage solver ?


geir

Mike Hansen

unread,
Aug 29, 2008, 7:56:15 PM8/29/08
to sage-s...@googlegroups.com
Hello,

On Fri, Aug 29, 2008 at 4:00 PM, geir.e...@gmail.com
<geir.e...@gmail.com> wrote:
> I want to construct a set of equations using strings. For example:
>
> for i in range(0,10):
> eq1="eq=x^"+str(i)+"-"+str(i)

Is there a reason why you wanted to do it using strings? It's a bit
cleaner/easier to do it without strings:
sage: eq = var('eq')
sage: eqs = [0== x^i - i for i in range(1,10)]
sage: eqs
[0 == x - 1,
0 == x^2 - 2,
0 == x^3 - 3,
0 == x^4 - 4,
0 == x^5 - 5,
0 == x^6 - 6,
0 == x^7 - 7,
0 == x^8 - 8,
0 == x^9 - 9]

But, I doubt that those are the actual equations you want. you just
need to modify the eqs = ... line to be what you need.

--Mike

Simon King

unread,
Aug 29, 2008, 8:12:34 PM8/29/08
to sage-support
Hi Geir,

If you really want to use strings, it may work like that:
sage: var('x y')
(x, y)
sage: EqL=['y==x**%d-%d'%(i,i) for i in range(10)]
sage: for X in EqL:
....: print X
....: print solve(eval(X))
....:
y==x**0-0
[
y == 1
]
y==x**1-1
[
x == y + 1
]
y==x**2-2
[
x == - sqrt(y + 2),
x == sqrt(y + 2)
]

etc...

Note that double-= yields an equation (not a boolean!) if symbolic
expressions such as x and y are involved. A single "=" is an
assignment.

Cheers
Simon

William Stein

unread,
Aug 29, 2008, 8:44:28 PM8/29/08
to sage-s...@googlegroups.com
On Fri, Aug 29, 2008 at 5:12 PM, Simon King <ki...@mathematik.uni-jena.de> wrote:
>
> Hi Geir,
>
> If you really want to use strings, it may work like that:
> sage: var('x y')
> (x, y)
> sage: EqL=['y==x**%d-%d'%(i,i) for i in range(10)]
> sage: for X in EqL:
> ....: print X
> ....: print solve(eval(X))

Use sage_eval instead of eval, unless you want to
confusing results:

sage: eval('2/3')
0
sage: eval('2^3')
1


> ....:
> y==x**0-0
> [
> y == 1
> ]
> y==x**1-1
> [
> x == y + 1
> ]
> y==x**2-2
> [
> x == - sqrt(y + 2),
> x == sqrt(y + 2)
> ]
>
> etc...
>
> Note that double-= yields an equation (not a boolean!) if symbolic
> expressions such as x and y are involved. A single "=" is an
> assignment.
>
> Cheers
> Simon
>
> >
>

--
William Stein
Associate Professor of Mathematics
University of Washington
http://wstein.org

geir egeland

unread,
Aug 30, 2008, 4:06:08 PM8/30/08
to sage-s...@googlegroups.com
Thank you for all the help. 
With your input, I managed to do what I wanted in Sage, and
can now finish my paper before the deadline:)

regards,  
Geir Egeland
phone +47 906 40 507
PhD Candidate
University of Stavanger
and 
Research Scientist
Telenor R&I 



Reply all
Reply to author
Forward
0 new messages