cpmul.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /* cpmul.c
  2. *
  3. * Multiply two polynomials with complex coefficients
  4. *
  5. *
  6. *
  7. * SYNOPSIS:
  8. *
  9. * typedef struct
  10. * {
  11. * double r;
  12. * double i;
  13. * }cmplx;
  14. *
  15. * cmplx a[], b[], c[];
  16. * int da, db, dc;
  17. *
  18. * cpmul( a, da, b, db, c, &dc );
  19. *
  20. *
  21. *
  22. * DESCRIPTION:
  23. *
  24. * The two argument polynomials are multiplied together, and
  25. * their product is placed in c.
  26. *
  27. * Each polynomial is represented by its coefficients stored
  28. * as an array of complex number structures (see the typedef).
  29. * The degree of a is da, which must be passed to the routine
  30. * as an argument; similarly the degree db of b is an argument.
  31. * Array a has da + 1 elements and array b has db + 1 elements.
  32. * Array c must have storage allocated for at least da + db + 1
  33. * elements. The value da + db is returned in dc; this is
  34. * the degree of the product polynomial.
  35. *
  36. * Polynomial coefficients are stored in ascending order; i.e.,
  37. * a(x) = a[0]*x**0 + a[1]*x**1 + ... + a[da]*x**da.
  38. *
  39. *
  40. * If desired, c may be the same as either a or b, in which
  41. * case the input argument array is replaced by the product
  42. * array (but only up to terms of degree da + db).
  43. *
  44. */
  45. /* cpmul */
  46. typedef struct
  47. {
  48. double r;
  49. double i;
  50. }cmplx;
  51. int cpmul( a, da, b, db, c, dc )
  52. cmplx *a, *b, *c;
  53. int da, db;
  54. int *dc;
  55. {
  56. int i, j, k;
  57. cmplx y;
  58. register cmplx *pa, *pb, *pc;
  59. if( da > db ) /* Know which polynomial has higher degree */
  60. {
  61. i = da; /* Swapping is OK because args are on the stack */
  62. da = db;
  63. db = i;
  64. pa = a;
  65. a = b;
  66. b = pa;
  67. }
  68. k = da + db;
  69. *dc = k; /* Output the degree of the product */
  70. pc = &c[db+1];
  71. for( i=db+1; i<=k; i++ ) /* Clear high order terms of output */
  72. {
  73. pc->r = 0;
  74. pc->i = 0;
  75. pc++;
  76. }
  77. /* To permit replacement of input, work backward from highest degree */
  78. pb = &b[db];
  79. for( j=0; j<=db; j++ )
  80. {
  81. pa = &a[da];
  82. pc = &c[k-j];
  83. for( i=0; i<da; i++ )
  84. {
  85. y.r = pa->r * pb->r - pa->i * pb->i; /* cmpx multiply */
  86. y.i = pa->r * pb->i + pa->i * pb->r;
  87. pc->r += y.r; /* accumulate partial product */
  88. pc->i += y.i;
  89. pa--;
  90. pc--;
  91. }
  92. y.r = pa->r * pb->r - pa->i * pb->i; /* replace last term, */
  93. y.i = pa->r * pb->i + pa->i * pb->r; /* ...do not accumulate */
  94. pc->r = y.r;
  95. pc->i = y.i;
  96. pb--;
  97. }
  98. return 0;
  99. }