Advertisement
joric

Fast and accurate fixedpoint sine/cosine on Java

Nov 13th, 2011
325
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.05 KB | None | 0 0
  1.     public static long[] isincos(long phasein) {
  2.         long sinout, cosout;
  3.         long OUTBITS = 16;
  4.         long BITSPERCYCLE = 16;
  5.         long BITSPERQUARTER = (BITSPERCYCLE - 2);
  6.         long BITS = 8;
  7.         long ONE = 1 << BITS;
  8.         long HALF = ONE / 2;
  9.         long C = 70710 * ONE / 100000;
  10.         // Modulo phase into quarter, convert to float 0..1
  11.         long modphase = (phasein & (1 << BITSPERQUARTER) - 1) * ONE / (1 << BITSPERQUARTER);
  12.         // Extract quarter bits
  13.         long quarter = phasein & (3 << BITSPERQUARTER);
  14.         // Recognize quarter
  15.         if (quarter == 0) {
  16.             // First quarter, angle = 0 .. pi/2
  17.             long x = modphase - HALF;      // 1 sub
  18.             long temp = ((2 * ONE - 4 * C) * x / ONE) * x / ONE + C; // 2 mul, 1 add
  19.             sinout = temp + x;              // 1 add
  20.             cosout = temp - x;              // 1 sub
  21.         } else if (quarter == 1 << BITSPERQUARTER) {
  22.             // Second quarter, angle = pi/2 .. pi
  23.             long x = HALF - modphase;      // 1 sub
  24.             long temp = ((2 * ONE - 4 * C) * x / ONE) * x / ONE + C; // 2 mul, 1 add
  25.             sinout = x + temp;              // 1 add
  26.             cosout = x - temp;              // 1 sub
  27.         } else if (quarter == 2 << BITSPERQUARTER) {
  28.             // Third quarter, angle = pi .. 1.5pi
  29.             long x = modphase - HALF;      // 1 sub
  30.             long temp = ((4 * C - 2 * ONE) * x / ONE) * x / ONE - C; // 2 mul, 1 sub
  31.             sinout = temp - x;              // 1 sub
  32.             cosout = temp + x;              // 1 add
  33.         } else {
  34.             // Fourth quarter, angle = 1.5pi..2pi
  35.             long x = modphase - HALF;      // 1 sub
  36.             long temp = ((2 * ONE - 4 * C) * x / ONE) * x / ONE + C; // 2 mul, 1 add
  37.             sinout = x - temp;              // 1 sub
  38.             cosout = x + temp;              // 1 add
  39.         }
  40.         long arr[] = new long[2];
  41.         arr[0] = sinout << (OUTBITS - BITS);
  42.         arr[1] = cosout << (OUTBITS - BITS);
  43.         return arr;
  44.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement