2

Consider the assumptions

$Assumptions = {Element[a,Reals], Element[z,Complexes]}

I'm looking for a test, to be applied on a and z, that gives True if the argument is a complex number such as a and False if it's real such as z.

The aim is to use this test in a replacement in this way

set = {a, z, x};
set /. (x_ :> img /; test[x])
(* {a, img, x} *)

An example is

set /. (x_ :> img /; Simplify[NotElement[x, Reals] && Element[x,Complexes]] === (NotElement[x, Reals]))

It is based on the fact that

Simplify[ Element[z,Reals] ]

remain unevaluated.

Is there another possible test that doesn't rest on this (and, possibly, simpler and without If and similar)?

corey979
  • 23,947
  • 7
  • 58
  • 101
Giancarlo
  • 712
  • 4
  • 11

2 Answers2

3

The following uses $Assumptions to loosely check if a symbol has a definition using a particular domain.

ClearAll[symbolDomainQ];
SetAttributes[symbolDomainQ, HoldFirst];

symbolDomainQ[s_Symbol, domain_] :=
 Or @@ Nor @@@ (Through@{FreeQ[s], FreeQ[domain]}[#] & /@ $Assumptions)

With

$Assumptions = {a ∈ Reals, z ∈ Complexes, m ∈ Matrices[{4, 4}, Reals, Symmetric[{1, 2}]]}

Then

{symbolDomainQ[a, Reals], symbolDomainQ[z, Complexes], symbolDomainQ[m, Reals]}
{True, True, True}
symbolDomainQ[m, Matrices]
True
symbolDomainQ[a, Complexes]
False

This only works if the symbols have not been assigned values. When they are assigned values $Assumptions changes so that it is not searchable for that symbol.

a = 1;
$Assumptions
a=.
{True, z ∈ Complexes, m ∈ Matrices[{4, 4}, Reals, Symmetric[{1, 2}]]}

It would be nice to have a built-in function that could check against the assumptions and work with or without a symbol having a value. Perhaps you should make a suggestion to WRI.

Hope this helps.

Edmund
  • 42,267
  • 3
  • 51
  • 143
  • Well, another practical solution, at least in my case, is this: starting from $Assumption, create a list with all real parameters, and after, using Complement, get a list with the complex parameters. With this list it's easy to create the test function just using MemberQ – Giancarlo Nov 18 '16 at 03:49
  • 1
    FWIW the definition of $Assumptions has not changed, only the way it evaluates. You can pull the held form using my step function from http://mathematica.stackexchange.com/a/1447/121 – Mr.Wizard Nov 20 '16 at 18:54
  • That is an interesting function. +1 – Edmund Nov 20 '16 at 19:35
0

There are a number of ways, e.g.:

f[x_] := With[{ri = ReIm /@ N[x]}, 
  ri /. {{_, 0} :> False, {_, _} :> True}]

Testing:

r = RandomReal[1, 10];
c = Complex @@@ RandomReal[1, {10, 2}];
test = Join[r, c][[RandomSample[Range@20]]];
Thread[{test, f[test]}] // Grid

enter image description here

ubpdqn
  • 60,617
  • 3
  • 59
  • 148
  • Hi ubpdqn, Thanks for your reply. Actually I'm looking for something that can work with symbols defined in the $Assumptions, not just with numbers. I've modified my question in order to be clearer. – Giancarlo Nov 15 '16 at 08:30