summaryrefslogtreecommitdiff
path: root/graphs/piscine/handling_complex/complex.c
blob: 79a10be4ef0831151e191e7920f783fa236637aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "complex.h"

#include <stdio.h>

void print_complex(struct complex a)
{
    printf("complex(%.2f ", a.real);

    if (a.img < 0)
    {
        printf("- %.2fi", -a.img);
    }
    else
    {
        printf("+ %.2fi", a.img);
    }
    printf(")\n");
}

struct complex neg_complex(struct complex a)
{
    struct complex z = { -a.real, -a.img };
    return z;
}

struct complex add_complex(struct complex a, struct complex b)
{
    struct complex z = { a.real + b.real, a.img + b.img };
    return z;
}

struct complex sub_complex(struct complex a, struct complex b)
{
    return add_complex(a, neg_complex(b));
}

struct complex mul_complex(struct complex a, struct complex b)
{
    struct complex z = { a.real * b.real - a.img * b.img,
                         a.real * b.img + a.img * b.real };
    return z;
}

struct complex div_complex(struct complex a, struct complex b)
{
    struct complex z = {
        (a.real * b.real + a.img * b.img) / (b.real * b.real + b.img * b.img),
        (a.img * b.real - a.real * b.img) / (b.real * b.real + b.img * b.img)
    };
    return z;
}