ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Wed, 01 May 2013 17:19:44 +0200Ignoring the very small imaginary parthttps://ask.sagemath.org/question/10024/ignoring-the-very-small-imaginary-part/I am generating a matrix that its entries come from roots of a polynomial which are all real. Due to calculation errors sage returns entries such as: `-2.8 + 2.2e-16*I`
How can I ask sage to ignore the small imaginary part and return -2.8?Wed, 01 May 2013 16:03:09 +0200https://ask.sagemath.org/question/10024/ignoring-the-very-small-imaginary-part/Answer by vdelecroix for <p>I am generating a matrix that its entries come from roots of a polynomial which are all real. Due to calculation errors sage returns entries such as: <code>-2.8 + 2.2e-16*I</code></p>
<p>How can I ask sage to ignore the small imaginary part and return -2.8?</p>
https://ask.sagemath.org/question/10024/ignoring-the-very-small-imaginary-part/?answer=14870#post-id-14870Hi,
I would prefer to have a method **.real()** for a complex matrix as there exists one for complex number::
sage: CC(1,0.5).real()
1.00000000000000
But it does not exist yet! Moreover, using **.real()** ignore all imaginary part. Here is a function that makes the job:
trunc_small_imag = lambda x: x.real() if abs(x.imag()) < .000001 else x
mat_trunc_small_imag = lambda m: m.parent()(map(trunc_small_imag, m.list()))
And here is an example:
sage: m = matrix([[CC(1,.0000001), CC(2,-0.5)],[CC(2,0.4),CC(1.1,-.000000004)]])
sage: mat_trunc_small_imag(m)
[ 1.00000000000000 2.00000000000000 - 0.500000000000000*I]
[2.00000000000000 + 0.400000000000000*I 1.10000000000000]
Wed, 01 May 2013 16:47:43 +0200https://ask.sagemath.org/question/10024/ignoring-the-very-small-imaginary-part/?answer=14870#post-id-14870Comment by k1 for <p>Hi,</p>
<p>I would prefer to have a method <strong>.real()</strong> for a complex matrix as there exists one for complex number::</p>
<pre><code>sage: CC(1,0.5).real()
1.00000000000000
</code></pre>
<p>But it does not exist yet! Moreover, using <strong>.real()</strong> ignore all imaginary part. Here is a function that makes the job:</p>
<pre><code>trunc_small_imag = lambda x: x.real() if abs(x.imag()) < .000001 else x
mat_trunc_small_imag = lambda m: m.parent()(map(trunc_small_imag, m.list()))
</code></pre>
<p>And here is an example:</p>
<pre><code>sage: m = matrix([[CC(1,.0000001), CC(2,-0.5)],[CC(2,0.4),CC(1.1,-.000000004)]])
sage: mat_trunc_small_imag(m)
[ 1.00000000000000 2.00000000000000 - 0.500000000000000*I]
[2.00000000000000 + 0.400000000000000*I 1.10000000000000]
</code></pre>
https://ask.sagemath.org/question/10024/ignoring-the-very-small-imaginary-part/?comment=17777#post-id-17777Thank you very much. It worked great. Wed, 01 May 2013 17:19:44 +0200https://ask.sagemath.org/question/10024/ignoring-the-very-small-imaginary-part/?comment=17777#post-id-17777