1

I have the following problem in Mathematica:

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

When I evaluate it the first time,everything works:

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])

But by evaluate it a second time several errors occurs:

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"
...

It seems to me, that the ReplaceRepeated in the if condition work global although it is a Module environment. Can anybody help? How I solve this problem?

4

1 回答 1

1

第一次评估你的代码

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 的值是多少?

In[13]:= x
Out[13]= 1/2 (-b - Sqrt[b^2 - 4 c])

那也行。现在开始第二次评估您的代码。

In[14]:= values = {b -> 1, c -> 0};
Solutions := Solve[x^2 + b*x + c == 0, x]

假设您现在要评估解决方案。这将在 x 中评估您的二次方,但您会看到 x 不再只是一个没有值的符号,它将使用 Out[13] 中 x 的值,解决方案是

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])]

这就是它失败的原因。您之前分配了 xa 值,您正在使用 x 并因此在 Solve 中使用该值。也许您想在评估所有这些之前清除您的 x。

于 2013-10-09T15:34:42.470 回答