3
$\begingroup$

If I have a variable such as

r = 1 + Sqrt[2] + Sqrt[13]

how can I separate that into two separate variables with the rational and irrational parts? i.e.

a = 1
b = Sqrt[2] + Sqrt[13]
$\endgroup$
  • $\begingroup$ In this simple case you could use {a, b} = {r[[1]], r[[2 ;;]]} or {aa, bb} = DeleteCases[r, #] & /@ {_Power, _Integer} $\endgroup$ – user1066 Jul 7 '18 at 9:13
  • $\begingroup$ Did any of the answers satisfied your need? There are things to do after your question is answered. It's a good idea to stay vigilant for some time, better approaches may come later improving over previous replies. Experienced users may point alternatives, caveats or limitations. New users should test answers before voting and wait 24 hours before accepting the best one. One weeks is enough wait. Participation is essential for the site, please do your part. $\endgroup$ – rhermans Jul 14 '18 at 21:44
6
$\begingroup$
{a, b} = Pick[r, Element[#, Rationals] & /@ List @@ r, #] & /@ {True, False}

{1, Sqrt[2] + Sqrt[13]}

$\endgroup$
  • $\begingroup$ Just what I was looking for, a nice simple one-line solution. Thanks. $\endgroup$ – Jerry Guern Jul 15 '18 at 21:16
3
$\begingroup$

In your example you could use Select:

r = 1 + Sqrt[2] + Sqrt[13];
a = Select[r, RootApproximant[#, 1] == # &]
b = Select[r, RootApproximant[#, 1] != # &]

The code above ignores symbolic terms leaving a warning. If === and =!= are used then the symbolic terms will be considered as irrational, but still with a warning.

However, there are infinitely many ways to write r as a sum of a rational and an irrational number. E.g. you could let a = 0 and b = r.

$\endgroup$
2
$\begingroup$

Following function picks up manifestly rational and irrational parts of a given number. It ignores unknown numbers (such as the variable a below). OP's example:

Clear[rationalPartChooser];
rationalPartChooser = Function[a, {
  Pick[#, Element[#, Rationals] & /@ #], 
  Pick[#, ! Element[#, Rationals] & /@ #]
  } &[List @@ a]
];

1 + a + Sqrt[2] // rationalPartChooser

{{1}, {Sqrt[2]}}

$\endgroup$
1
$\begingroup$
With[
  {
   r = 1 + Sqrt[2] + Sqrt[13]
   },
  {a, b} = {Select[r, NumberQ], Select[r, Not@*NumberQ]}
  ];

a
(* 1 *)

b
(* Sqrt[2] + Sqrt[13] *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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