使用C++中的std :: complex <T>创建复杂的无穷大

End*_*yto 14 c++ nan infinity complex-numbers numeric-limits

我正在尝试创建一个等于Inf + Inf*j的复数无穷大,其中j是复数变量.当我这样做:

#include <complex>
#include <limits>
using std;

...

complex<double> attempt1 =
   complex<double>( numeric_limits<double>::infinity(),
                    numeric_limits<double>::infinity() );
Run Code Online (Sandbox Code Playgroud)

返回复数(NaN + Inf*j).

complex<double> attempt2 =
   complex<double>( numeric_limits<double>::infinity() );
Run Code Online (Sandbox Code Playgroud)

返回复数(Inf + 0*j).

另外:

complex<double> attempt_at_imag_inf =
   complex<double>(any_value_here, numeric_limits<double>::infinity());
Run Code Online (Sandbox Code Playgroud)

返回复数(NaN + Inf*j).

有谁知道这里发生了什么?任何时候我试图为想象的部分提供信息,那么NaN就写在真实的部分上.

以上仅适用于支持NaN和Infinity的类型.我正在使用g ++ v4.6.1.我查看了numeric_limits标题,并没有迹象表明上面应该发生.

为了将上述内容置于上下文中,我实际上是在对numeric的一个部分特殊化中执行上述操作.非常感谢您考虑这个问题.

修改原始邮政

我正在提供一个完整但很短的程序来说明问题.我还提供了一些关于如何编译程序以生成结果的更多合格信息.

#include <iostream>
#include <complex>
#include <limits>

using namespace std;

int main(int argc, char* argv[])
{

   complex<double> my_complex_inf =
      complex<double>(numeric_limits<double>::infinity(),
                      numeric_limits<double>::infinity());

   cout << "my_complex_inf = " << my_complex_inf << endl;

   complex<double> attempt2 =
      complex<double>( numeric_limits<double>::infinity() );

   cout << "attempt2 = " << attempt2 << endl;

   double any_value_here = 0;

   complex<double> attempt_at_imag_inf =
      complex<double>(0, numeric_limits<double>::infinity());

   cout << "attempt_at_imag_inf = " << attempt_at_imag_inf << endl;

   return 0;

}
Run Code Online (Sandbox Code Playgroud)

使用-std = c ++ 0x在Ubuntu上用g ++版本4.6.1编译上面的内容给出了以下结果:

my_complex_inf = (nan,inf)
attempt2 = (inf,0)
attempt_at_imag_inf = (nan,inf)
Run Code Online (Sandbox Code Playgroud)

如果没有-std = c ++ 0x选项,结果为:

my_complex_inf = (inf,inf)
attempt2 = (inf,0)
attempt_at_imag_inf = (0,inf)
Run Code Online (Sandbox Code Playgroud)

所以问题确实是为什么GNU g ++ V4.6.1在指定C++ 0x时给出了答案?

修订2原始邮政

我刚刚在Octave(类似MATLAB的数字包)中尝试了以下内容:

a = inf + j*inf

答案是:

a = NaN + Infi

这正是我在C++ 11代码(C++ 0x)中看到的.我不知道Octave是用什么编译的(它是我认为的C++和FORTRAN的组合)但是如果那个包返回我得到的结果,那么我认为这是众所周知的行为.

但是,我已经查看了C++ 11草案标准,并且找不到任何关于此行为的提及.

修订3原始邮寄

添加以下行

my_complex_inf.real(my_complex_inf.imag());
Run Code Online (Sandbox Code Playgroud)

在为C++ 11编译时,my_complex_inf构造之后返回"正确"答案(inf,inf).不幸的是,现在这是一个两步过程,我无法在constexpr函数中创建这种复杂的无穷大.

Chr*_*odd 5

您遇到了 C++11(和 C11)指定复数的方式并感到困惑。

基本上,在规范规定的模型中,只有一个无穷大(用 (inf,0) 表示),并且尝试将“无穷大”放入 Nan 中的复数结果的虚部中,因为它在那个型号。


小智 4

标量 Inf 转换为复数为 inf+0 j。上面这个是正确的。复平面中的标量 Inf 偏移意味着旋转,且不可计算,因此 Nan 是正确的。又是什么问题呢?

“有龙。”