Question

Lets say I want to calculate Vout where Vout = (Vin/((I*w*R*C)+1)); where "i" should be defined as the sqrt(-1) . How do I do that in Objective-C?

Was it helpful?

Solution

You can #include <complex.h> then use either _Complex_I or I macros (note the uppercase). The type of variables that contains complex values are denoted with the _Complex attribute, which can also be written simply complex.

double complex c1 = 1.0 + 2.0 * I; // 1+2i
double complex c2 = 2.0 + 3.0 * I; // 2+3i
double complex sum = c1 + c2;
double complex mul = c1 * c2;

You can then use the creal and cimag functions to get real and imaginary parts of a complex.

So in your case:

double Vin = 20; // in Volts
double w = 60; // frequency of your sinusoidal source (60Hz)
double R = 50; // 50 ohms
double C = 20e-6; // 20 µF
double complex invertZc = I*w*C; // Zc = 1/jwC, invertZc = jwC
double complex Vout = Vin / (1. + R*invertZc); // Vout = Vin * 1.0 / (1+Zr/Zc)

Note that all this is provided by the GNU C language (see here), and are not specifically part of Objective-C itself but come from GNU C (Objective-C being a superset of C) and its extensions (which are supported by the GCC and LLVM compilers used by Xcode)

OTHER TIPS

Objective C does not have any built-in facility for handling complex numbers. You have to do the calculations yourself. Create a typedef of a struct imaginaryNumber that contains a real and imaginary part. Write functions that add and multiply those structures and return another one as a result. (To multiply 2 complex numbers (a1+b1i)•(a2+b2i) you treat the numbers as polynomials and use the FOIL method to calculate the result. The product of the 2 imaginary terms becomes a real number because i • i = -1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top