Consider an expression of the form $a + b \sqrt{2}$, where $a,b \in \mathbb{Q}$. How can I extract $b$ (or equivalently $a$) from this expression?


2 Answers 2


One can define the conjugate and use it to construct the rational and radical coefficients (rat and rad resp.). Just as PowerExpand assumes bases are positive reals, conj[x] will be correct only if the symbolic variables and functions in an expression x represent rational numbers.

conj[x_] := x /. Sqrt[2] -> -Sqrt[2];
rat[x_] := (x + conj[x])/2;
rad[x_] := (x - conj[x])/(2 Sqrt[2]);

Through[{rat, rad}[a + b Sqrt[2]]]
  {a, b}

Through[{rat, rad}[(a + b Sqrt[2])^2]]
% // Simplify

  { 1/2 ((a - Sqrt[2] b)^2 + (a + Sqrt[2] b)^2),
    (-(a - Sqrt[2] b)^2 + (a + Sqrt[2] b)^2)/(2 Sqrt[2]) }
  {a^2 + 2 b^2, 2 a b}

Simplify@Through[{rat, rad}[(3 - 2 Sqrt[2])/10]]
  {3/10, -(1/5)}

More generally, one can extend the definitions to numbers over an arbitrary quadratic extension of the rationals.

Clear[conj, rat, rad];
conj[x_, sqroot_: Sqrt[2]] := x /. sqroot -> -sqroot;
rat[x_, sqroot_: Sqrt[2]] := (x + conj[x, sqroot])/2;
rad[x_, sqroot_: Sqrt[2]] := (x - conj[x, sqroot])/(2 sqroot);
  • $\begingroup$ Yes, of course. Very clever solution. $\endgroup$ Dec 4, 2014 at 17:09

You can use ToNumberField:

2/3 + 1/4 Sqrt[2]
ToNumberField[%, Sqrt[2]]

which produces

AlgebraicNumber[Sqrt[2], {2/3, 1/4}]
  • $\begingroup$ Very nice. Thanks! $\endgroup$ Dec 4, 2014 at 15:39
  • $\begingroup$ What if $a$ and $b$ are symbolic? $\endgroup$ Dec 4, 2014 at 15:41
  • $\begingroup$ @TysonWilliams: I'm not sure how to handle that case, as I rarely use the abstract algebra functions. However, Daniel Lichtblau might know how to do it, so you could try asking him (or you could ask it as another question). $\endgroup$ Dec 4, 2014 at 15:48
  • $\begingroup$ As a mathematician / theoretical computer scientist, I think of $a$ and $b$ as "symbolically rational" (i.e. some rational numbers by assumption). Of course I also know, but often forget, that (1) symbolic, (2) symbolically rational, and (3) and rational are three different "data types" that can all behave differently in Mathematica. $\endgroup$ Dec 4, 2014 at 16:18
  • 1
    $\begingroup$ BTW: One can use ToNumberField[num][[2, 1]] to extract the rational part ("a") of any quadratic field. No need to even specify the generator! $\endgroup$
    – kirma
    Feb 1, 2016 at 21:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.