Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the imaginary part of a complex number to zero?

I need to check if the imaginary part is very small and set it to zero if it is in order to eliminate some floating point errors that result in very small non-zero imaginary parts when it should be zero.

My code is as follows:

kz2 = SQRT((n2*(2.0*PI*eta))**2 - kxarray(p)**2)
kz1 = SQRT((n1*(2.0*PI*eta))**2 - kxarray(p)**2)

if (aimag(kz2) < 0.0005) then
    kz2 = (REAL(kz2),0.0)
end if

if (aimag(kz1) < 0.0005) then
    kz1 = (REAL(kz1), 0.0)
end if

Unfortunately the compiler just returns:

gaussian1.f90:122.18:

kz2 = (REAL(kz2),0.0)
                1
Error: Expected a right parenthesis in expression at (1)

gaussian1.f90:126.18:

kz1 = (REAL(kz1), 0.0)
                1
Error: Expected a right parenthesis in expression at (1)

Any advice would be greatly appreciated - am I even going about this problem the right way?

UPDATE: I managed to avoid the problem by using:

if (aimag(kz2) < 0.0005) then
    kz2 = real(kz2)
end if

if (aimag(kz1) < 0.0005) then
    kz1 = real(kz1)
end if

But what would I do if I wanted to set the imaginary part to a non-zero amount?

like image 930
Alex McMurray Avatar asked Dec 02 '22 00:12

Alex McMurray


2 Answers

In Fortran 2008 there are even more possibilities. You can access real and imaginary parts as derived type components, e.g.

   a = c%re
   b%im = 5

So, to set imaginary part of z to zero in new compilers you can try z%im = 0 .

like image 53
Vladimir F Героям слава Avatar answered Dec 03 '22 13:12

Vladimir F Героям слава


I think you are looking for the CMPLX function, which converts real or integer arguments to a complex number. So it you example you should be able to do something like this:

kz1 = cmplx(real(kz1), 0.)

The (1.0,1.0) style parenthesis notation you have tried is only valid for constant values, not forming a complex number from the values held in variables.

like image 43
talonmies Avatar answered Dec 03 '22 14:12

talonmies