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?

edit retag close merge delete

Sort by » oldest newest most voted

Hi,

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]
more