Fast transcendent / trigonometric functions for Java

前端 未结 12 1836
面向向阳花
面向向阳花 2020-11-29 02:06

Since the trigonometric functions in java.lang.Math are quite slow: is there a library that does a quick and good approximation? It seems possible to do a calculation severa

12条回答
  •  萌比男神i
    2020-11-29 02:36

    Computer Approximations by Hart. Tabulates Chebyshev-economized approximate formulas for a bunch of functions at different precisions.

    Edit: Getting my copy off the shelf, it turned out to be a different book that just sounds very similar. Here's a sin function using its tables. (Tested in C since that's handier for me.) I don't know if this will be faster than the Java built-in, but it's guaranteed to be less accurate, at least. :) You may need to range-reduce the argument first; see John Cook's suggestions. The book also has arcsin and arctan.

    #include 
    #include 
    
    // Return an approx to sin(pi/2 * x) where -1 <= x <= 1.
    // In that range it has a max absolute error of 5e-9
    // according to Hastings, Approximations For Digital Computers.
    static double xsin (double x) {
      double x2 = x * x;
      return ((((.00015148419 * x2
                 - .00467376557) * x2
                + .07968967928) * x2
               - .64596371106) * x2
              + 1.57079631847) * x;
    }
    
    int main () {
      double pi = 4 * atan (1);
      printf ("%.10f\n", xsin (0.77));
      printf ("%.10f\n", sin (0.77 * (pi/2)));
      return 0;
    }
    

提交回复
热议问题