2013-10-09 59 views
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 

當我第一次評估它,一切正常:

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

但通過評估它第二次幾個錯誤發生:

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

在我看來,該ReplaceRepeated在if條件をrk全球雖然它是一個模塊環境。任何人都可以幫忙嗎?我如何解決這個問題?

回答

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不再僅僅是一個沒有價值的象徵,它要使用x的值在輸出[13]和解決方案是

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。

相關問題