如何将复数的虚部设置为零? [英] How to set the imaginary part of a complex number to zero?

查看:395
本文介绍了如何将复数的虚部设置为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查虚部是否很小,并将其设置为零,以消除一些浮点误差,这些浮点误差在虚部应为零时导致非常小的非零虚部。



我的代码如下:

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

如果(aimag(kz2)<0.0005)则
kz2 =(REAL(kz2),0.0)
如果

if(aimag( kz1)< 0.0005)然后
kz1 =(REAL(kz1),0.0)
如果

不幸的是,编译器仅返回:

  gaussian1.f90:122.18:

kz2 =(REAL(kz2),0.0)
1
错误:期望在(1)

gaussian1.f90:126.18:
$中有右括号b $ b kz1 =(REAL(kz1),0.0)
1
错误:期望在(1)


任何建议都是非常感谢-我什至会以正确的方式解决这个问题?



更新:我设法通过使用以下方法避免了该问题:

  if(aimag(kz2)< 0.0005)然后
kz2 =实数(kz2)
如果

如果(aimag(kz1)<0.0005)则
kz1 =实数(kz1)$ b如果

$ b结尾,但是如果我想将虚部设置为非零金额?

解决方案

我认为您正在寻找 CMPLX 函数,将实数或整数参数转换为复数。因此,在您的示例中,您应该能够执行以下操作:

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

(1.0,1.0)样式的括号您尝试过的符号仅对常量值有效,而不能从变量中的值形成复数。


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?

解决方案

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.

这篇关于如何将复数的虚部设置为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆