开发者

Constant in Python Sage? Variable getting wiped out after use

Yesterday I began messing around with Sage, an open source computer algebra system. Sage uses Python to bind several open-source packages into one coding interface.

Unfortunately, not only was Sage new, Python was as well. I spent the better part of today learning both. What can I say? Once a nerd, always a nerd...

The problem came when I began looking at vector systems in multiple dimensions.

As you can see below, I am trying to use var('w') to encapsulate the variables x,y,z. This would allow me to say f(w) instead of f(x,y,z). Really handy when you have multiple equations. The problem is that after I use w the first time, it gets reset to 'w'.

Short of continually reassigning w to "x,y,z" is there any way to set a constant? It does not look like it according to the specs on Python's web page.

As a PS, my solution to the problem strikes me as sort of clumsy. I am not a student, but a 40-something nerd, amazed at the technology available today. So I have no TA or professor or fellow students to ask for help.

My s开发者_如何学Colution...

1) Define another variable:

v=var('v')

v=(x,y,z)

2) After each run through a function--f(x), g(x), h(x)--reassigning the value w=v

Thanks, Leo

***Code****

x=var('x')
y=var('y')
z=var('z')
w=var('w')

w=(x,y,z); print(w) #prints out 'x,y,z'

f(w) = ((2*x - y + 0*z)==0); print(w) #prints out 'w'
g(w) = ((-x + 2*y - z)==-1); print(w) #prints out 'w'
h(w) = ((0*x - 3*y + 4*z)==4); print(w) #prints out 'w'

solve((f(w), g(w), h(w)), w)) #returns errors since it needs to be 
#solved in x,y,z, not w


w=var('w'): w is a symbol object with name 'w'.

w=(x,y,z): w is a tuple of three symbol objects. To use this tuple to define expression function, you can use "*" to unpack the tuple: f(*w) is the same as f(x,y,z), when w==(x,y,z).

So, the following code will do solve() correctly:

x=var('x')
y=var('y')
z=var('z')

w=(x,y,z)

f(*w) = (2*x - y + 0*z)==0
g(*w) = (-x + 2*y - z)==-1
h(*w) = (0*x - 3*y + 4*z)==4

solve((f,g,h), w)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜