Sum of complex numbers expressed in polar form - c

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);
}

^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

Related

setting value of array c

I'm trying to implement polynomials in C but Im having an issue with arrays and setting values. Im bad at C, please explain why this is happening: I run this, it says that p.coefs[1] is 0.0 instead of 3.0 as intended.
#include <stdio.h>
#include <assert.h>
int main()
{
#define MAX_DEG 10
typedef struct Polynomial Polynomial;
struct Polynomial {
int deg;
double coefs[MAX_DEG];
};
Polynomial ply_create(int deg) {
assert(deg >= 0 && deg <= MAX_DEG);
Polynomial poly;
poly.deg = deg;
return poly;
}
void ply_set_coef(Polynomial poly, int i, double val) {
poly.coefs[i] = val;
}
Polynomial p = ply_create(1);
p.coefs[0] = 1.0;
ply_set_coef(p, 1, 3.0);
printf("p.coefs[0] is %f and p.coefs[1] is %f", p.coefs[0], p.coefs[1]);
return 0;
}
I was previously using malloc and made p.coefs a pointer to a double. In this case I did not have any problem.

How does typedef with tuples work?

We got this typedef in a homework program. As a programmer noob, I didn't see anything like this before. Does this mean that any DoubleFunction2D is actually a 2-tuple of (double, double)?
Program:
typedefs:
typedef double (*DoubleFunction) (double);
typedef double (*DoubleFunction2D) (double, double);
typedef double (*DoubleFunction3D) (double, double, double);
Example usage
(my WIP solution to a task, not yet complied/tested. Inside):
double expf2D(double x, double y)
{
double r = sqrt(pow(x,2) + pow(y,2));
return my_expf(r);
}
double DiskMonteCarloIntegrator(DoubleFunction2D f, double r1, double r2, int N)
{
bool is_inside_ring(double x, double y){
return is_inside_ellipse(x, y, r2/2, r2/2) && !(is_inside_ellipse(x, y, r1/2, r1/2));
}
int i=0;
double x, y, sum = 0;
while(i < N)
{
x = RandomDouble(-1*r1, r1);
y = RandomDouble(-1*r1, r1);
if(is_inside_ring(x, y))
{
sum += f(x, y);
i++;
}
}
double avg = sum / N;
double integral = avg * (pow(r2, 2) - pow(r1, 2)) * M_PI;
return integral;
}
//extract
void main(int argc, char *argv[]){
DiskMonteCarloIntegrator(expf2D, 1.0, 2.0, 1000000);
}
There are no tuples here (in fact, there are no "tuples" in the C programming language).
typedef double (*DoubleFunction) (double);
means DoubleFunction is a pointer to a function that takes a double and returns a double.
typedef double (*DoubleFunction2D) (double, double);
means DoubleFunction2D is a pointer to a function that takes two double values and returns a double.
typedef double (*DoubleFunction3D) (double, double, double);
means DoubleFunction3D is a pointer to a function that takes three double values and returns a double.

Using Custom Vectors in C

I'm fairly new to C/C++, but I'm trying to debug some code. It uses a vector that someone had called CART8 and is structured as such:
typedef struct crt8 {
double x;
double y;
double z; } CART8;
Now my question is this. How do I create and populate an instance of an vector of type CART8 called vector1? I've read through a lot of material, and even found a site that indicate how you would create the vector...as indicated above, but no information on HOW to actually use it.
typedef is used extensively in C to refer to struct variables without specifying the struct prefix, for example if I had:
struct vector {
double x;
double y;
double z;
};
than to initialize it I'd have to do:
struct vector vector1;
vector1.x = 1.11;
vector1.y = 1.22;
vector1.z = 1.33;
But if I used a typedef in the declaration:
typedef struct vector {
double x;
double y;
double z;
} vector_type;
than I could simplify this initialization like so (note the struct prefix is not needed now):
vector_type vector1;
vector1.x = 1.11;
vector1.y = 1.22;
vector1.z = 1.33;
Of course, I could still use the full struct vector initialization in this case as well
So in your case:
#include <stdio.h>
typedef struct crt8 {
double x;
double y;
double z;
} CART8;
int main(int argc, char** argv)
{
CART8 vector1;
vector1.x = 2.526;
vector1.y = 3.416;
vector1.z = 4.32;
printf("%f %f %f\n", vector1.x, vector1.y, vector1.z);
}
Alternatively, you can always resort to the original struct definition:
#include <stdio.h>
typedef struct crt8 {
double x;
double y;
double z;
} CART8;
int main(int argc, char** argv)
{
struct crt8 x;
x.x = 2.341;
x.y = 3.43;
x.z = 4.521;
printf("%f %f %f\n", x.x, x.y, x.z);
}
You wrote:
typedef struct crt8 {
double x;
double y;
double z;
} CART8;
This defined a new 'type'. The 'typename' is struct crt8 or the alias you defined CART8. This is how you instantiate an object from that type in C:
struct crt8 myVector;
or you can use the alias 'CART8' that you've defined:
CART8 myVector;
Either way, this is how you populate the 'members' of your object:
CART8 x; // Creation of object
x.x = 100;
x.y = 101;
x.z = 102;
Here is a demonstrative program that shows various ways how objects of the structure can be created, initialized, and used.
#include <stdio.h>
#include <math.h>
typedef struct crt8 {
double x;
double y;
double z; } CART8;
int main( void )
{
CART8 vector1 = { 1.1, 2.2, 3.3 };
CART8 vector2 = { .x = 1.1, .y = 2.2, .z = 3.3 };
CART8 vector3;
vector3.x = 1.1;
vector3.y = 2.2;
vector3.z = 3.3;
CART8 vector4 = vector1;
CART8 vector5 = { vector1.x + vector2.z, vector1.y + vector2.y, vector1.z + vector2.x };
printf( "vector5 = { %lf, %lf, %lf }\n", vector5.x, vector5.y, vector5.z );
printf( "Magnitude = %lf", sqrt( pow( vector1.x, 2 ) + pow( vector1.y, 2 ) + pow( vector1.z, 2 ) ) );
return 0;
}
The output is
vector5 = { 4.400000, 4.400000, 4.400000 }
Magnitude = 4.115823

Casting data array to compatible struct

I'm in a situation where my code receives data from somewhere beyond my control in the form of a long list of floats.
These numbers get distributed to various functions
void myfunc(struct floatstruct* fs);
that take structs of the following form:
struct floatstruct
{
float a;
float b;
float c;
};
You get the idea.
I was wondering if there is a way to safely cast the array of floats to floatstruct to pass the data directly on to myfunc. I can add alignment attributes to floatstruct if necessary.
Example of desired behaviour:
struct mystruct1
{
float a;
float b;
float c;
};
struct mystruct2
{
float x;
float y;
};
extern void myfunc1(mystruct1*);
extern void myfunc2(mystruct2*);
void process_data(float* numbers)
{
myfunc1((struct mystruct1*)numbers);
myfunc2((struct mystruct2*)(numbers + 3));
}
The ideal solution is surely to change the system. But I'm looking for solutions within the given parameters.
Here's what I would do, given your peculiar requirements: ( I say this because 3 new floats here or there will make literally no noticeable difference unless you plan to use this on an arduino or phone or if you plan on having like tens of thousands...)
Anyways:
struct floatstruct
{
float (*a[3]);
};
{
int i;
struct floatstruct aStruct;
struct floatstruct bStruct;
float *num = numbers;
for (i = 0; i < 6; i++) {
if (i < 3)
aStruct.a[i] = num;
else
bStruct.a[i-3] = num;
num++;
}
myfunc1(&aStruct);
myfunc2(&bStruct);
}
Union could be what you need:
#pragma pack(sizeof(float))
struct mystruct1
{
float a;
float b;
float c;
};
struct mystruct2
{
float x;
float y;
};
#pragma pack()
typedef union
{
mystruct1 struct1;
mystruct2 struct2;
}structsUnion;
void myfunc1(structsUnion* values)
{
values->struct1.a; // to access members
}
void myfunc2(structsUnion* values)
{
values->struct2.x; // to access members
}
void process_data(float* numbers)
{
myfunc1((structsUnion*)(numbers));
myfunc2((structsUnion*)(numbers));
}

C Typedef Struct / Union auto-cast

Im having a small math library for 3d vector and Im trying to "unify" it.
Instead of having multiple typedef struct for vector3f, vector3i, color3, angles etc... Im trying to put everything inside the same struct like this:
typedef struct
{
union
{
float x;
float r;
float ax;
int x_int;
};
union
{
float y;
float g;
float ay;
int y_int;
};
union
{
float z;
float b;
float az;
int z_int;
};
} vec3;
Everything works peachy as long as the type is float, however when it falls to int Im having some strange values (which is understandable). My question is: Is there a way to cast directly/automatically inside the structure definition or I have to create extra functions to typecast between float and int?
Due to the answers below, maybe I should modify my original question to the following:
What is the best way to "unify" (and by unify I mean have like 1 struct) to be able to handle at the same time the following:
vector3f (float x,y,z)
vector3i (int x,y,z)
RGB (float r,g,b)
RGB (unsigned char r,g,b)
euler angle (ax, ay, az)
Thanks in advance!
If you mean that you want to put '360.0f' into float z of a union and have int z_int == 3, or vice versa, you can't. That is not the purpose of a union, and the binary representation of 3 (an integer) and 3.0 (a floating point value) are dissimiliar.
However, you could just remove the int and cast one of the floats to an int.
#include <stdio.h>
#include <stdlib.h>
typedef struct genericStruct
{
void *valueOne;
void *valueTwo;
}GS;
int main()
{
GS *gs = malloc(sizeof(*gs));
int valueInt = 10;
float valueFloat = 3.141592653589;
int *inputIntPtr = (int*)malloc(sizeof(int));
float *inputFloatPtr = (float*)malloc(sizeof(float));
void *voidPtr = NULL;
*inputIntPtr = valueInt;
*inputFloatPtr = valueFloat;
voidPtr = inputIntPtr;
gs->valueOne = voidPtr;
int *outputIntPtr = (int*)malloc(sizeof(int));
outputIntPtr = gs->valueOne;
printf("Input ptr = %d\n", *inputIntPtr);
printf("Output ptr = %d\n", *outputIntPtr);
voidPtr = inputFloatPtr;
gs->valueTwo = voidPtr;
float *outputFloatPtr = (float*)malloc(sizeof(float));
outputFloatPtr = gs->valueTwo;
printf("Input ptr = %f\n", *inputFloatPtr);
printf("output ptr = %f\n", *outputFloatPtr);
free(gs);
free(inputIntPtr);
free(inputFloatPtr);
free(outputIntPtr);
free(outputFloatPtr);
return 0;
}
And this what I meant by using void types.
This is a small piece of code that i wrote for you.It should do the job.I hope i was able to do what you asked for...
typedef struct{
void *ptr1;
void *ptr2;
void *ptr3;
}VEC;
main(){
VEC v ;
VEC *ptr;
int a = 5;
double b = 6;
float c = 7;
v.ptr1 = NULL;
v.ptr2 = NULL;
v.ptr3 = NULL;
ptr = &v;
v.ptr1 = (int *)&a;
ptr->ptr1 = (int *)&a;
v.ptr2 = (double *)&b;
ptr->ptr2 = (double *)&b;
v.ptr3 = (float *)&c;
ptr->ptr3 = (float *)&c;
printf("%d\n",*(int *)v.ptr1);
printf("%d\n",*(int *)(ptr->ptr1));
printf("%lf\n",*(double *)v.ptr2);
printf("%lf\n",*(double *)(ptr->ptr2));
printf("%f\n",*(float *)v.ptr3);
printf("%f\n",*(float *)(ptr->ptr3));
}
Or change all variables to void pointer type and then cast them to float or integer. Is it OK?

Resources