Python Sage 中的常量?变量在使用后被清除
昨天我开始摆弄 Sage,一个开源计算机代数系统。 Sage 使用 Python 将多个开源包绑定到一个编码接口中。
不幸的是,不仅 Sage 是新的,Python 也是新的。我今天大部分时间都在学习这两件事。我能说什么?曾经是书呆子,永远是书呆子……
当我开始研究多维向量系统时,问题就出现了。
正如您在下面看到的,我尝试使用 var('w') 来封装变量 x,y,z。这允许我说 f(w) 而不是 f(x,y,z)。当你有多个方程时真的很方便。问题是,在我第一次使用 w 后,它被重置为“w”。
除了不断地将 w 重新分配给“x,y,z”之外,还有什么方法可以设置一个常量吗?根据 Python 网页上的规范,它看起来并不像它。
作为一名 PS,我对这个问题的解决方案让我觉得有点笨拙。我不是学生,而是一个 40 多岁的书呆子,对当今的技术感到惊讶。所以我没有助教、教授或同学可以寻求帮助。
我的解决方案...
1)定义另一个变量:
v=var('v')
v=(x,y,z)
2) 每次运行函数后——f(x)、g(x)、h(x)——重新分配值 w=v
谢谢, 狮子座
***代码*< /em>***
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
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 solution...
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
w=var('w'): w 是一个名为 'w' 的符号对象。
w=(x,y,z):w 是三个符号对象的元组。要使用这个元组定义表达式函数,可以使用“*”来解压元组:当w==(x,y,z)时,f(*w)与f(x,y,z)相同。
因此,以下代码将正确执行solve():
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: