Search code examples
c++complex-numbers

Complex number array multiplication


Is there a multiplication version to the operation a *= b for complex number arrays? In other words, what is the most efficient way to multiply all elements of an array of complex numbers (large number of elements or of unknown length) and store the result in a complex double variable?

In the following code, Ans1 provides the correct answer, however, for my application it won't make sense to address each element of the array as there will be hundreds. Ideally, I'd want to have a loop (something similar to Ans2) that multiplies all elements of the array and store the answer. If I don't initiate Ans2 as 1.0,1.0 the answer will be 0,0 as the elements will be multiplied by 0. However, initializing with 1.0,1.0 wouldn't work either as we're dealing with complex numbers.

EDIT - The reason I can't address each element manually is because this will be linked to a bigger programe where the elements of the array a will come from somewhere else, and the length of a will vary.

Ideally ANSWER = COMPLEX ELEMENT[0]*COMPLEX ELEMENT[1]*COMPLEX ELEMENT[2]*....COMPLEX ELEMENT[n]

/*
  Complex Array Multiplication
*/

#include <complex>
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int n = 3;
    complex<double> Ans1, Ans2(1.0,1.0);

    complex<double> a[n];

    a[0] = complex<double>(1.0, 1.5);
    a[1] = complex<double>(-1.0, 1.5);
    a[2] = complex<double>(1.0, -1.5);

    Ans1 = (a[0]*a[1]*a[2]);
    cout << "\nAns1 = " << Ans1;

    for (int i =0; i < n; i++) {
        Ans2 = Ans2 * a[i];
    }

    cout << "\nAns2 = " << Ans2;

    getchar();
}

Maybe this could be done very easily but I'm missing something. Thanks in advance.


Solution

  • The multiplicative identity for complex numbers is 1 + 0i, so you should initialize Ans2 to (1, 0) prior to your loop.

    In case you're not familiar with the term, an identity is a value that doesn't change the result of an operation. For example, the additive identity for real numbers is 0 because a + 0 = a for any real value a. For multiplication of complex numbers, (a + bi) * (1 + 0i) = (a + bi). In your loop, you want to initialize Ans2 to a value that won't affect the result of the calculation, so you use the multiplicative identity.