首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数学将军::伊瓦尔..。不是有效的变量。

数学将军::伊瓦尔..。不是有效的变量。
EN

Stack Overflow用户
提问于 2013-10-09 11:30:29
回答 1查看 2.6K关注 0票数 1

我的数学有以下问题:

代码语言:javascript
复制
values = {b -> 1, c -> 0};
Solutions := Solve[x^2 + b*x + c == 0, x]
x1 := x /. Solutions[[1]];
x2 := x /. Solutions[[2]];
"Solution 1"
x1
"Solution 2"
x2
"Choose ~preferred~ Solution, which is -1 when using values"
If[Module[{list = values}, ReplaceRepeated[x1 == -1, list]], x = x1, x = x2]
"~Preferred~ Solution"
x

当我第一次评估它时,一切都正常:

代码语言:javascript
复制
Solution 1
1/2 (-b - Sqrt[b^2 - 4 c])
Solution 2
1/2 (-b + Sqrt[b^2 - 4 c])
Choose ~preferred~ Solution, which is -1 when using values
1/2 (-b - Sqrt[b^2 - 4 c])

但是,通过第二次评估,会出现以下几个错误:

代码语言:javascript
复制
Solution 1
General::ivar: 1/2 (-b-Sqrt[b^2-4 c]) is not a valid variable. >>
General::ivar: 1/2 (-b-Sqrt[b^2-4 c]) is not a valid variable. >>
ReplaceAll::reps: {1/2 b (-b-Sqrt[Plus[<<2>>]])+1/4 (-b-Power[<<2>>])^2+c==0} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>
1/2 (-b - Sqrt[b^2 - 4 c]) /. 
1/2 b (-b - Sqrt[b^2 - 4 c]) + 1/4 (-b - Sqrt[b^2 - 4 c])^2 + c == 0
"Solution 2"
...

在我看来,if条件中的ReplaceRepeated似乎是全局工作的,尽管它是一个模块环境。有人能帮忙吗?我是怎么解决这个问题的?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-09 15:34:42

第一次评估您的代码

代码语言:javascript
复制
In[1]:= values = {b -> 1, c -> 0};
Solutions := Solve[x^2 + b*x + c == 0, x]
x1 := x /. Solutions[[1]];
x2 := x /. Solutions[[2]];
"Solution 1"
x1
"Solution 2"
x2
"Choose ~preferred~ Solution, which is -1 when using values"
If[Module[{list = values}, ReplaceRepeated[x1 == -1, list]], x = x1, x = x2]
"~Preferred~ Solution"
x

Out[5]= "Solution 1"
Out[6]= 1/2 (-b - Sqrt[b^2 - 4 c])
Out[7]= "Solution 2"
Out[8]= 1/2 (-b + Sqrt[b^2 - 4 c])
Out[9]= "Choose ~preferred~ Solution, which is -1 when using values"
Out[10]= 1/2 (-b - Sqrt[b^2 - 4 c])
Out[11]= "~Preferred~ Solution"
Out[12]= 1/2 (-b - Sqrt[b^2 - 4 c])

一切都很好。现在x的值是多少?

代码语言:javascript
复制
In[13]:= x
Out[13]= 1/2 (-b - Sqrt[b^2 - 4 c])

这很好。现在开始第二次评估您的代码。

代码语言:javascript
复制
In[14]:= values = {b -> 1, c -> 0};
Solutions := Solve[x^2 + b*x + c == 0, x]

假设您现在想要评估解决方案。这将在x中求出你的二次型,但你会看到x不再只是一个没有值的符号,它将在Out13中使用x的值,解决方案是

代码语言:javascript
复制
In[15]:= Solutions

During evaluation of In[15]:= Solve::ivar: 1/2 (-b-Sqrt[b^2-4 c]) is not a valid variable. >>

Out[15]= Solve[1/2b(-b-Sqrt[b^2-4c])+1/4(-b-Sqrt[b^2-4c])^2+c==0, 1/2(-b-Sqrt[b^2-4c])]

这就是它失败的原因。您以前为x分配了一个值,在解决方案中使用了x,因此也使用了这个值。也许您想在评估所有这些之前清除您的x。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19270831

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档