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

I need to check if the imaginary part is very small and sets it to zero if it is designed to eliminate some floating point errors that lead to very small non-zero imaginary parts when they 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 simply 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 - have I really solved this problem correctly?

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 nonzero sum?

+4
source share
2 answers

I think you are looking for a CMPLX function that converts real or integer arguments to a complex number. So you, for example, can do something like this:

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

The indicated tag bracket (1.0,1.0) that you tried is valid only for constant values, without forming a complex number from the values ​​stored in the variables.

+9
source

Fortran 2008 has even more features. You can access real and imaginary parts as components of a derived type, for example.

  a = c%re b%im = 5 

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

+8
source

Source: https://habr.com/ru/post/1401783/


All Articles