How to programing with complex number in cprograming.

Discussion in 'Programmer's Corner' started by xinzlee, Dec 4, 2007.

  1. xinzlee

    Thread Starter Member

    Nov 19, 2007
    13
    0
    I face the problem when want programing by using sum, dived, multi, minus in complex number... so how to do it.
     
  2. Dave

    Retired Moderator

    Nov 17, 2003
    6,960
    144
    Do you have a programming language that you are thinking of? If you use something like Matlab there is syntax dedicate to complex numbers, otherwise it is no too difficult to understand the basic concepts of +-*/ for complex numbers.

    Dave
     
  3. Papabravo

    Expert

    Feb 24, 2006
    10,144
    1,790
    In C the easiest way to do what you want is to use a structure with two members representing the real part and the imaginary part.

    Code ( (Unknown Language)):
    1.  
    2. typedef struct complex_t
    3. {
    4.     float r ;
    5.     float i ;
    6. } COMPLEX ;
    7.  
    8. static COMPLEX    r1 ;
    9.  
    10. COMPLEX *cadd(COMPLEX *a, COMPLEX *b)
    11. {
    12.      r1.r = a->r + b->r ;     /* Add real parts  */
    13.      r1.i = a->i + b->i ;     /* Add imaginary parts   */
    14.      return &r1 ;             /* Return pointer to structure  */
    15. }
    16.  
    17. COMPLEX *pr1 ;
    18. COMPLEX c1, c2 ;
    19. void main(void)
    20. {
    21.     c1.r = 2.1 ; c1.i = 4.3 ;
    22.     c2.r = 1.6 ; c2.i = 3.2 ;
    23.  
    24.     pr1 = cadd(&c1, &c2) ;
    25. /*
    26. **    pr1->r should be 3.7
    27. **    pr1->i should be 7.5
    28. */
    29. }
    30.  
    31.  
    The reason for using pointers is that many compilers will not allow the passing of arrays and structures by value which is the common convention in C compilers. The the value passed needs to be a pointer to the object.
     
Loading...