Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typecasting std::complex<double> to __complex128

I'm trying to use the quadmath library in GCC. I have a complex double value I'd like to typecast into the corresponding quad precision complex number, __complex128. The following is a minimal (non)-working example:

#include <quadmath.h>
#include <complex>
#include <stdio.h>
using namespace std::complex_literals;

int main(){
   std::complex<double> x = 1 + 2i;
   std::printf("x = %5.5g + %5.5g\n", x.real(), x.imag()); 
   __complex128 y = 2+2i;
   y = x;
  return 0;
}

When I try compiling this code with

 g++ test.cpp -lquadmath -o test

I get the following error:

test.cpp:10:6: error: cannot convert 'std::complex<double>' to '__complex128 {aka __complex__ __float128}' in assignment
y = x;

If I try replacing the assignment line with an explicit type cast,

y = (__complex128) x;

I get a similar error

test.cpp:10:21: error: invalid cast from type 'std::complex<double>' to type '__complex128 {aka __complex__ __float128}'
y = (__complex128) x;

How does one convert between these two types?

like image 621
Jeff Avatar asked Jan 21 '17 05:01

Jeff


1 Answers

I guess you're using GCC, in which case you can use the __real__ and __imag__ extensions to set the individual components of your __complex128:

__complex128 y;
__real__ y = x.real();
__imag__ y = x.imag();

This works in Clang for __complex64, too (Clang doesn't yet support __complex128).

like image 94
nneonneo Avatar answered Oct 15 '22 03:10

nneonneo