How to set the imaginary part of a complex number

2020-03-25 02:03发布

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?

2条回答
神经病院院长
2楼-- · 2020-03-25 02:38

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 .

查看更多
看我几分像从前
3楼-- · 2020-03-25 02:53

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.

查看更多
登录 后发表回答