EE_13
EE_13

Reputation: 11

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!

Upvotes: 0

Views: 2708

Answers (1)

rts1
rts1

Reputation: 1466

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

Upvotes: 3

Related Questions