October 23, 2011
C : Complex Number Computation
In this post, I will create program C : complex number computation.
Are you know about complex number? A complex number is a number consisting of a real part and an imaginary part. Computation for real/integer number is different with complex number. In this tutorial, I am write how we can process complex number computation. Complex number computation from this code consists of :
- cadd : add two complex numbers
- csub : subtract two complex numbers
- cmul : multiply two complex numbers
- cdiv : divide two complex numbers
- cmplx : make a complex number from two real numbers
- conjg : complex conjugate of a complex number
- cneg : negate a complex number
- cinv : invert a complex number
- csqrt : complex square root of a complex number
- cexp : complex exponential of a complex number
- crmul : multiply a complex number by a real number
- rcabs : real magnitude of a complex number
This is a sample tes code how to process complex number compution, save this code as complex_computation.c :
/*
* main.c
*
* Created on: Oct 23, 2011
* Author: toto
*/
#include "complex.h"
int main(int argc, char **argv)
{
float far, fai, fbr, fbi;
complex A, B, C;
char type, type1;
if(argc==6)
{
sscanf(argv[1],"%f",&far);
sscanf(argv[2],"%f",&fai);
sscanf(argv[3],"%f",&fbr);
sscanf(argv[4],"%f",&fbi);
sscanf(argv[5],"%c%c%c",&type1, &type1, &type);
}
else
{
printf("help :\n");
printf("use : ./complex_computation r1 i1 r2 i2 --type\n");
printf("\nexample: ./complex_computation 1 5 3 -6 --+ \n");
return(0);
}
A = cmplx(far, fai); //create A complex data
B = cmplx(fbr, fbi); //create B complex data
printf("\n--- COMPLEX NUMBER COMPUTATION --- \n");
cplx_print("A =", A); //print complex A
cplx_print("B =", B); //print complex B
printf("------------------------- %c ", type);
if(type=='^')
printf("0.5\n");
else
printf("\n");
switch(type)
{
case '+':
C = cadd(A,B);
break;
case '-':
C = csub(A,B);
break;
case '*':
C = cmul(A,B);
break;
case '/':
C = cdiv(A,B);
break;
case '^':
C = c_sqrt(A);
break;
default:
C = cadd(A,B);
break;
}
cplx_print("C =", C); //print complex C
return(1);
}
This is example how to use and output for complex number computation above code :
~/workspace/complex_computation$ ./complex_computation 3.3 4.5 3.4 5.6 --/ --- COMPLEX NUMBER COMPUTATION --- A = 3.30000 + 4.50000i B = 3.40000 + 5.60000i ------------------------- / C = 0.84856 - 0.07409i
You can download the complete source code complex number computation code at here.
Source : http://www.cwp.mines.edu/cwpcodes/ http://en.wikipedia.org/wiki/Complex_number