gsl_linalg__balance.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* linalg/balance.c
  2. *
  3. * Copyright (C) 2001, 2004, 2007 Brian Gough
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or (at
  8. * your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful, but
  11. * WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; if not, write to the Free Software
  17. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. */
  19. /* Balance a general matrix by scaling the columns
  20. *
  21. * B = A D
  22. *
  23. * where D is a diagonal matrix
  24. */
  25. #include "gsl__config.h"
  26. #include <stdlib.h>
  27. #include "gsl_math.h"
  28. #include "gsl_vector.h"
  29. #include "gsl_matrix.h"
  30. #include "gsl_blas.h"
  31. #include "gsl_linalg.h"
  32. int
  33. gsl_linalg_balance_columns (gsl_matrix * A, gsl_vector * D)
  34. {
  35. const size_t N = A->size2;
  36. size_t j;
  37. if (D->size != A->size2)
  38. {
  39. GSL_ERROR("length of D must match second dimension of A", GSL_EINVAL);
  40. }
  41. gsl_vector_set_all (D, 1.0);
  42. for (j = 0; j < N; j++)
  43. {
  44. gsl_vector_view A_j = gsl_matrix_column (A, j);
  45. double s = gsl_blas_dasum(&A_j.vector);
  46. double f = 1.0;
  47. if (s == 0.0 || !gsl_finite(s))
  48. {
  49. gsl_vector_set (D, j, f);
  50. continue;
  51. }
  52. /* FIXME: we could use frexp() here */
  53. while (s > 1.0)
  54. {
  55. s /= 2.0;
  56. f *= 2.0;
  57. }
  58. while (s < 0.5)
  59. {
  60. s *= 2.0;
  61. f /= 2.0;
  62. }
  63. gsl_vector_set (D, j, f);
  64. if (f != 1.0)
  65. {
  66. gsl_blas_dscal(1.0/f, &A_j.vector);
  67. }
  68. }
  69. return GSL_SUCCESS;
  70. }