Re: Real Solutions
- To: mathgroup at smc.vnet.net
- Subject: [mg95812] Re: Real Solutions
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Wed, 28 Jan 2009 06:27:52 -0500 (EST)
- Organization: The Open University, Milton Keynes, UK
- References: <glmssi$mkr$1@smc.vnet.net>
In article <glmssi$mkr$1 at smc.vnet.net>, Kowalczyk-Schröder wrote:
> I need only the real solutions from Solve or NSolve. I found a
> complicated way with a lot of "ifs" to get, what I want. Is there an
> easier way to do this? (I don't want to use Reduce.)
I think that one of the easiest ways to achieve what you are looking for
is by using *DeleteCases* as in
DeleteCases[sols, {s_Rule} /;
Head[Chop[N[Last[s]]]] === Complex, Infinity]
Note that Solve may return complex solutions as Complex[] expressions,
fractional powers of negative bases, Root[] objects, or a mix of two or
three of those constructs. So we are looking for the lists that contain
a rule for which its second element numerically evaluates to Complex[].
For NSolve,
DeleteCases[sols, {s_Rule} /;
Head[Chop[Last[s]]] === Complex, Infinity]
would suffice.
In[1]:= sols = Solve[x^2 + 1 == 0]
sols // N
DeleteCases[sols, {s_Rule} /;
Head[Chop[N[Last[s]]]] === Complex, Infinity]
Out[1]= {{x -> -I}, {x -> I}}
Out[2]= {{x -> 0.- 1. I}, {x -> 0.+ 1. I}}
Out[3]= {}
In[4]:= sols = Solve[x^5 + x^4 + x^3 + x^2 + x + 1 == 0]
sols // N
DeleteCases[sols, {s_Rule} /;
Head[Chop[N[Last[s]]]] === Complex, Infinity]
Out[4]= {{x -> -1}, {x -> -(-1)^(1/3)}, {x -> (-1)^(
1/3)}, {x -> -(-1)^(2/3)}, {x -> (-1)^(2/3)}}
Out[5]= {{x -> -1.}, {x -> -0.5 - 0.866025 I}, {x ->
0.5+ 0.866025 I}, {x ->
0.5- 0.866025 I}, {x -> -0.5 + 0.866025 I}}
Out[6]= {{x -> -1}}
In[7]:= sols = Solve[x^5 + 2 x + 1 == 0, x]
sols // N
DeleteCases[sols, {s_Rule} /;
Head[Chop[N[Last[s]]]] === Complex, Infinity]
Out[7]= {{x -> Root[1 + 2 #1 + #1^5 &, 1]}, {x ->
Root[1 + 2 #1 + #1^5 &, 2]}, {x ->
Root[1 + 2 #1 + #1^5 &, 3]}, {x ->
Root[1 + 2 #1 + #1^5 &, 4]}, {x -> Root[1 + 2 #1 + #1^5 &, 5]}}
Out[8]= {{x -> -0.486389}, {x -> -0.701874 -
0.879697 I}, {x -> -0.701874 + 0.879697 I}, {x ->
0.945068- 0.854518 I}, {x -> 0.945068+ 0.854518 I}}
Out[9]= {{x -> Root[1 + 2 #1 + #1^5 &, 1]}}
Regards,
--Jean-Marc