复数为-1的Fortran sqrt给出不同的结果 [英] Fortran sqrt of complex number -1 gives different results

查看:140
本文介绍了复数为-1的Fortran sqrt给出不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码

print *, sqrt(cmplx(-1))
print *, sqrt(cmplx(-1,0))
print *, sqrt((-1,0))
print *, sqrt(-(1,0))

为我提供此输出

(0.00000000,1.00000000)
(0.00000000,1.00000000)
(0.00000000,1.00000000)
(0.00000000,-1.00000000)

我相信正确的代数是 sqrt(-1)= i 。为什么最后一行结果呢?

I believe that the correct algebra is sqrt(-1)=i. Why the result of the last line?

编译器版本为GCC 7.3.0,运行在Linux openSUSE 42.2(x86_64)上。

The compiler version is GCC 7.3.0, running on Linux openSUSE 42.2 (x86_64).

EDIT

在@francescalus回答之后,我尝试了更多的情况:

Following @francescalus answer I have tried more cases:

print *, sqrt((-1,-0))
print *, sqrt((-1,-0.))
print *, (-1,-0)
print *, (-1,-0.)

我得到

(0.00000000,1.00000000)
(0.00000000,-1.00000000)
(-1.00000000,0.00000000)
(-1.00000000,-0.00000000)

因此,看来我的编译器支持<$ c的负零$ c>实数数字。因此,我想在使用像这样的变量时要特别小心:

So, it seems that my compiler support negative zeros for real numbers. So, I guess it is important to care when working with variables like this:

complex             :: asd 
asd=(1.,0.)
print *, sqrt(-asd)

这里再次得到错误的结果,但是零负数则更难以预测。我有很多问题!您是否知道其他一些可能导致错误的示例?您是否有建议可以避免这种错误?您现在是否有一些编译器标记来关闭对GCC编译器的负面支持?

Here I get again the wrong result, but the zero negative thing is more difficult to predict. I have so many questions! Do you know some other exmple that can induce a mistake? Do you have an advice to avoid this mistakes? Do you now some compiler flag to turn off the negative cero support for the GCC compiler?

推荐答案

Fortran 2008(13.7.159)为参数 X 定义 sqrt 函数的结果,作为(我强调):

Fortran 2008 (13.7.159) defines the result of the sqrt function, for argument X, as (my emphasis):


结果的值等于与处理器有关的X平方根的近似值。类型complex的结果是主值,且实部大于或等于零。 当结果的实部为零时,虚部与X的虚部具有相同的符号。

您的平方根确实确实有零个实部,因此让我们看一下论证虚部的符号。 -(1,0)的虚部的符号是什么?如果您的处理器支持带符号的零,则可能为负。在这种情况下,根据标准的要求,结果的虚部应该为负。

Your square roots do indeed have zero real part, so let's look at the sign of the imaginary part of your argument. What is the sign of the imaginary component of -(1,0)? If your processor supports signed zero, then it could well be negative. In which case, the imaginary part of the result should be negative according to the standard's requirement.

在所有其他情况下,没有理由期望虚部该参数为负而不是正零。

In all other cases, there'd be no reason to expect the imaginary component of the argument to be negative, rather than positive, zero.

这篇关于复数为-1的Fortran sqrt给出不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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