Skip to content

Commit 1777bc8

Browse files
authored
Create complex_add.c
Function to add up two complex numbers.
1 parent e5dad3f commit 1777bc8

1 file changed

Lines changed: 74 additions & 0 deletions

File tree

math/complex_add.c

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/**
2+
* @file
3+
* @brief Function to add up two complex numbers.
4+
*/
5+
#define _USE_MATH_DEFINES /**< required for MS Visual C */
6+
#include <assert.h>
7+
#include <stdio.h>
8+
#include <stdlib.h>
9+
10+
/**
11+
* @brief Function to add two complex numbers.
12+
*\f{eqnarray*}{
13+
x + yi &=& (x_1 + y_1i) + (x_2 + y_2i)
14+
x &=& x_1 + x_2
15+
y &=% y_1 + y_2
16+
\f}
17+
* @param [in] x1 real part of the first summand
18+
* @param [in] y1 imaginary part of the first summand
19+
* @param [in] x2 real part of the second summand
20+
* @param [in] y2 imaginary part of the second summand
21+
* @param [out] x pointer to real part of the sum
22+
* @param [out] y pointer to imaginary part of the sum
23+
*/
24+
void summing(double x1, double y1, double x2, double y2, double *x, double *y)
25+
{
26+
*x = x1 + x2;
27+
*y = y1 + y2;
28+
}
29+
30+
/**
31+
* @brief Generate a random number in the given limits
32+
*
33+
* @param lim1 lower limit
34+
* @param lim2 upper limit
35+
* @return random number in the given range
36+
*/
37+
double get_rand(double lim1, double lim2)
38+
{
39+
double r = (double)rand() / RAND_MAX; // value in [0,1)
40+
return (lim2 - lim1) * r + lim1; // scale to range
41+
}
42+
43+
/**
44+
* @brief Test implementation
45+
*
46+
*/
47+
void test()
48+
{
49+
srand(10);
50+
int NUM_TESTS = 5;
51+
52+
for (int i = 0; i < NUM_TESTS; i++)
53+
{
54+
double x, y;
55+
printf("Test %d.... ", i);
56+
double x1 = get_rand(-5, 5);
57+
double y1 = get_rand(-5, 5);
58+
double x2 = get_rand(-5, 5);
59+
double y2 = get_rand(-5, 5);
60+
printf("(%.2g + %.2g i) + (%.2g + %.2g i)", x1, y1, x2, y2);
61+
summing(x1, y1, x2, y2, &x, &y);
62+
assert(fabs(x - (x1 + x2)) < 0.01);
63+
assert(fabs(y - (y1 + y2)) < 0.01);
64+
printf("passed\n");
65+
}
66+
}
67+
68+
/** Main function */
69+
int main()
70+
{
71+
test();
72+
73+
return 0;
74+
}

0 commit comments

Comments
 (0)