Search code examples
cstructstructurecomplex-numbers

Sum of complex numbers expressed in polar form


I need to sum two complex numbers (c1,c2) and then express the result in its polar form.

I don't really know how to access the result for c1+c2, I mean I store them in the variable "result" but when I try to access them I find myself in the ComplexPolar structure and so I can't access the result.real and result.img to calculate magnitude and angle:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

struct ComplexCartesian
{
    float real;
    float img;
};

struct ComplexPolar
{
    float magnitude;
    float angle;
};

struct ComplexPolar add_two_complex(struct ComplexCartesian c1, struct ComplexCartesian c2, struct ComplexPolar result)
{
    result.real= c1.real+c2.real;
    result.img=c1.img+c2.img;

    result.magnitude= sqrt((result.real)^2 + (result.img)^2);
    result.angle= atan2(result.img, result.real);
}

Solution

  • ^2 is not how you square in C, you have to either multiply the number by itself or use libc pow function.

    ^2 is a XOR operation where you aim to toggle the second bit, but in your case you are using it on a float which violates the strict aliasing rule and cause undefined behavior (on top of not being what you seek).

    See the code below with some comments:

    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    struct ComplexCartesian
    {
        float real;
        float img;
    };
    
    struct ComplexPolar
    {
        float magnitude;
        float angle;
    };
    
    struct ComplexPolar polar_from_cartesian_sum(struct ComplexCartesian c1, struct ComplexCartesian c2)
    {
        struct ComplexPolar complexPolar; // here you declare the variable of your ComplexPolar struct
    
        c1.real += c2.real; // you don't need to have a result var, you can just reuse c1.
        c1.img += c2.img;
        complexPolar.magnitude = sqrt(c1.real * c1.real + c1.img * c1.img);
        complexPolar.angle = atan2(c1.img, c1.real);
    
        return complexPolar; // you return the value;
    }
    
    
    int main(void) {
        struct ComplexCartesian c1 = {0.12f, 0.15f};
        struct ComplexCartesian c2 = {0.42f, 1.15f};
        struct ComplexPolar complexPolar = polar_from_cartesian_sum(c1, c2);
    
        printf("%f %f\n", complexPolar.magnitude, complexPolar.angle);
    
        return 0;
    }
    

    Compile with gcc complex.c -lm && ./a.out

    Output:

    1.407693 1.177098
    

    NB: Perhaps you should explicitly tell that your angle is expressed in radians, and also rename your function as polar_from_cartesian_sum

    Radius = 1.41
    θ = 67.44o = 1.18 radians