Advertisement
Guest User

Untitled

a guest
Nov 27th, 2014
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. /* solving the matrix equation A*x=b using LAPACK */
  2. #include <vecLib/clapack.h>
  3. #include <stdlib.h>
  4. #include <math.h>
  5. #include <stdio.h>
  6. #include "nrutil.h"
  7. #include <time.h>
  8.  
  9. #define NR_END 1
  10.  
  11.  
  12. float *vector(long nl, long nh)
  13. /* allocate a float vector with subscript range v[nl..nh] */
  14. {
  15. float *v;
  16.  
  17. v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
  18.  
  19. return v-nl+NR_END;
  20. }
  21.  
  22. float **matrix(long nrl, long nrh, long ncl, long nch)
  23. /* allocate a float matrix with cubscript range m[nrl..nrh][ncl..nch] */
  24. {
  25. long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
  26. float **m;
  27.  
  28. /* allocate pointers to rows */
  29. m=(float **) malloc((size_t)((nrow+NR_END)*sizeof(float*)));
  30.  
  31. m += NR_END;
  32. m -= nrl;
  33.  
  34. /* allocate rows and set pointers to them */
  35. m[nrl]=(float *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(float)));
  36.  
  37. m[nrl] += NR_END;
  38. m[nrl] -= nrl;
  39.  
  40. for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
  41.  
  42. /* return pointer to array of pointers to rows */
  43. return m;
  44. }
  45.  
  46.  
  47.  
  48. int solve_lin_eq_LAPACK ( float **A, float *B, int n ){
  49.  
  50. double Afortran[n*n], Btmp[n];
  51. int i,j, nb=1, check, Bpivot[n];
  52. int fail=0;
  53.  
  54. for (i=0; i<n; i++){ /* to call a Fortran routine from C we */
  55. /* have to transform the matrix to an array*/
  56. Btmp[i]=(double)B[i+1];
  57. for(j=0; j<n; j++){
  58. Afortran[j+n*i]=(double)A[j+1][i+1];
  59. }
  60. }
  61.  
  62. /*here for general matrix, but if A is symmetric (no-force case) one could
  63. actually use a special subroutine for those like ssysv_(...) (LAPACK)*/
  64. dgesv_(&n, &nb, Afortran, &n, Bpivot, Btmp, &n, &check);
  65. printf("check value=%i\n",check);
  66. if (check!=0) {
  67. printf("dgesv failed!\n");
  68. printf("check value=%i\n",check);
  69. fail=1;
  70. }
  71.  
  72. if (fail==0){
  73. for (i=0; i<n; i++)
  74. B[i+1]=(float)Btmp[i];
  75. }
  76. return(fail);
  77.  
  78. }
  79.  
  80. int main(){
  81.  
  82. float **A, *B;
  83. int fail;
  84.  
  85. A=matrix(1,3,1,3);
  86. B=vector(1,3);
  87.  
  88. A[1][1]=1674.456299;
  89. A[1][2]=-874.579834;
  90. A[1][3]=-799.876465;
  91. A[2][1]=-874.579834;
  92. A[2][2]=1799.875854;
  93. A[2][3]=-925.296021;
  94. A[3][1]=-799.876465;
  95. A[3][2]=-925.296021;
  96. A[3][3]=1725.172485;
  97. B[1]=74.703453;
  98. B[2]=-1799.875854;
  99. B[3]=1725.172241;
  100.  
  101.  
  102.  
  103. fail=solve_lin_eq_LAPACK ( A, B, 3 );
  104. printf("%f %f %f\n",B[1],B[2],B[3]);
  105. return(0);
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement