简体   繁体   中英

How to convert a complex<float> variable into a float in C++?

I have a variable in my code that is a complex float. I know that it only has a real part and I just want to type cast it to a float variable.

This should be super simple I feel but you can't just type cast and can't find the answer anywhere after over an hour of searching. Any help would be greatly appreciated!

There really isn't a "default" way to cast from a complex<float> to a float , because there are many interpretations:

  1. Do you want the magnitude of the complex number? ( sqrt(re*re + im*im) )
  2. Do you want the magnitude squared? This avoids the expensive square root.
  3. Do you want the real portion only?

Some frameworks that do a lot with Digital Signal Processing (such as X-Midas, Midas 2K, PicklingTools) explicitly do not allow such conversions. They make the user pick the appropriate conversion so the user doesn't lose information in the transformation . Having said, if you want just the real component, I feel some of the answers above were fine. Here's a full, standalone program that illustrates:

#include <complex>
#include <iostream>
using namespace std;

int main()
{
  complex<float> cf(1.1, 2.2);
  float real_portion_only = cf.real();

  cout << real_portion_only << endl;
}

The compile line and run looks like:

  % g++ comp.cc -o comp
  % ./comp
  1.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM