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

a 夏天 提交于 2019-12-30 10:15:09

问题


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?


回答1:


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.




回答2:


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 .



来源:https://stackoverflow.com/questions/9735559/how-to-set-the-imaginary-part-of-a-complex-number-to-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!