Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematica: Extract numerical value when using Solve

In Mathematica, calling Solve, returns a list of rules, e.g.,

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

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

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

Please advise.

like image 489
hbt Avatar asked Aug 23 '11 14:08

hbt


2 Answers

To complement Belisarius' answer,

x /. g

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

{1, 2}

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

First[x /. g]

Other alternatives are

x /. g[[1]]
(x /. g)[[1]]    (* this is equivalent to the version using First *)
g[[1,1,2]]
like image 185
Simon Avatar answered Oct 06 '22 01:10

Simon


x /. g[[1]]

Filler -> Thirty chars minimum

like image 32
Dr. belisarius Avatar answered Oct 06 '22 01:10

Dr. belisarius