Mathematica: Extract a numerical value using a solution

In Mathematica, calling Solve returns a list of rules, for example,

 In[1]:= g = Solve[(x - 1) (x - 2) == 0, x] Out[1]= {{x -> 1}, {x -> 2}} 

How can I extract numerical values 1 or 2 from g ?

I tried using Part , for example, g[[1]] , but it returns {x -> 1} , not 1 .

Please inform.

+6
source share
2 answers
 x /. g[[1]] 

Filler → At least thirty characters

+9
source

To complement Belisarius’s answer,

 x /. g 

with g = {{x -> 1}, {x -> 2}} , returns a list

 {1, 2} 

So, to extract the first value, 1 , we could use

 First[x /. g] 

Other alternatives

 x /. g[[1]] (x /. g)[[1]] (* this is equivalent to the version using First *) g[[1,1,2]] 
+10
source

Source: https://habr.com/ru/post/895682/


All Articles