Advertisement
Guest User

Untitled

a guest
Feb 25th, 2020
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. #include "matrix.h"
  2. #include "mex.h"
  3. #include <complex.h>
  4. #include <math.h>
  5.  
  6. using namespace std;
  7.  
  8. #define EPS 1e-8
  9.  
  10. void mexQuadsolve(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
  11.  
  12. enum {
  13. MAX_NLHS = 3,
  14. };
  15.  
  16. if (nlhs < 2 || nlhs > 3) {
  17. mexErrMsgIdAndTxt("MATLAB:cubesolve:output_arguments",
  18. "number of output arguments must be 2 or 3");
  19. }
  20.  
  21. size_t mrows = mxGetM(prhs[0]);
  22. size_t ncols = mxGetN(prhs[0]);
  23. for (int i = 0; i < nlhs; ++i) {
  24. plhs[i] = mxCreateDoubleMatrix((mwSize) mrows, (mwSize) ncols, mxCOMPLEX);
  25. }
  26.  
  27. mxComplexDouble *res[MAX_NLHS];
  28. for (int i = 0; i < nlhs; ++i) {
  29. res[i] = (mxComplexDouble *) mxGetComplexDoubles(plhs[i]);
  30. }
  31.  
  32. mxComplexDouble *A = (mxComplexDouble *) mxGetComplexDoubles(prhs[0]);
  33. mxComplexDouble *B = (mxComplexDouble *) mxGetComplexDoubles(prhs[1]);
  34. mxComplexDouble *C = (mxComplexDouble *) mxGetComplexDoubles(prhs[2]);
  35. __complex__ roots[] = {0, 0, 0};
  36.  
  37. for (size_t i = 0; i < mrows * ncols; ++i) {
  38. if (A[i].real * A[i].real + A[i].imag * A[i].imag < EPS) {
  39. mexErrMsgIdAndTxt("MATLAB:cubesolve:null_coeff",
  40. "A must be not null");
  41. }
  42.  
  43. __complex__ p = (B[i].real + I * B[i].imag) / (A[i].real + I * A[i].imag);
  44. __complex__ q = (C[i].real + I * C[i].imag) / (A[i].real + I * A[i].imag);
  45. __complex__ w = csqrt(cpow(p / 3., 3.0) + cpow(q / 2., 2.0));
  46. __complex__ alpha = cpow(-q / 2. + w, 1.0 / 3.0);
  47. // and here we need to rotate our beta becauose cpow calculates wrong branch
  48. // of logarithm inside computing the complex power
  49. __complex__ beta = cpow(-q / 2. - w, 1.0 / 3.0) * (-0.5 - I * csqrt(3) / 2);
  50.  
  51. roots[0] = -0.5 * (alpha + beta) + I * sqrt(3) / 2.0 * (alpha - beta);
  52. roots[1] = -0.5 * (alpha + beta) - I * sqrt(3) / 2.0 * (alpha - beta);
  53.  
  54. if (nlhs == 3) {
  55. roots[2] = alpha + beta;
  56. }
  57.  
  58. for (int k = 0; k < nlhs; ++k) {
  59. res[k][i].real = creal(roots[k]);
  60. res[k][i].imag = cimag(roots[k]);
  61. }
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement