2

This question has already been answered here:

Why does C++ mandate that complex only be instantiated for float, double, or long double?

However, I do not see how the answer there is valid. The accepted reason is that:

You can't properly implement many of the std::complex operations on integers. E.g.,

template T abs(const complex &z);

for a complex cannot have T = long return value...

However, I don't see any reason why not.

For example, if I have 1234567 + 7654321i, then the abs() is about 7753243.557. An integer result such as 7753243 or 7753244 could be highly useful. It doesn't matter which result is given, as long as the mechanism is consistent. (In the same way that we accept 5 / 3 = 1).

Could anyone offer any ideas as to why complex integers are not available?

Community
  • 1
  • 1
Harry
  • 884
  • 1
  • 8
  • 19
  • do you mean [Gaussian integers](http://en.wikipedia.org/wiki/Gaussian_integer) ? – M.M Nov 05 '14 at 20:57
  • IDK for sure, but it's not clear to me what you expect `abs(std::complex(3, 5))` to do. In any case it's simple enough for you to write your own class to implement whatever you want to do. – M.M Nov 05 '14 at 21:01
  • See http://stackoverflow.com/questions/11108743/ for a good explanation – uesp Nov 05 '14 at 21:02
  • Thanks for the link uesp. However, I don't really understand why "only a few of the operations would make sense". In particular, I don't follow what is said about the abs() function. (For example, see my comment in response to Mad Physicist, below). I don't really see how the answer accepted at that link is valid. – Harry Nov 05 '14 at 21:19
  • Matt, I would expect abs(std::complex(3, 5)) to return either 5 or 6. It doesn't matter which, as long as the mechanism is consistent. (In the same way that 5 / 3 = 1). – Harry Nov 05 '14 at 21:26

1 Answers1

-1

In mathematical terms, the absolute value of a complex number is the square root of the sum of the squares of its components. This means that only in very rare cases, like 3 + 4i, will the absolute value be an integer (5 for this example). If you want the absolute value to be of the same type as the template parameter, then you are SOL.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • Of course, there could be rounding error (and this rounding error will often be larger than when using floating point types), but I don't see a problem with that. For example, if I have '1234567 + 7654321i', then the abs() is about 7753243.557. An integer result such as 7753243 or 7753244 could be highly useful. – Harry Nov 05 '14 at 21:16