The difference in the speed of calculating trigonometric functions in Java and C#


I am studying Java and became interested in the work of the method sin (cos). I noticed that the rate of getting the sine on j varies depending on the argument of the function. If the angle is less than 0.785... rad, it calculates quickly, and if it is more than that, it calculates slowly.

Compared with C#, it turned out about the opposite:

enter a description of the image here

Checked in milliseconds for 10 million sine calculations.
Why are the results like this?


Here is the result for java cosine/sine from 0 to 4*pi:

enter a description of the image here


public static void main(String[] args) {        
    long a;
    for (double x = 0; x < 4 * Math.PI; x = x + 0.05) {
        a = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            //Math.cos(x);
            Math.sin(x);
        }
        System.out.printf("%.6f, %d \n", x, (System.currentTimeMillis() - a));
    }
}

Here is the result for the cosine/sine of C# from 0 to 4*pi:

enter a description of the image here

public static void Main(string[] args)
    {
        for (double x = 0; x < 4 * Math.PI; x = x + 0.05) {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 10000000; i++) {
                Math.Cos(x);
                // Math.Sin(x);
            }
            sw.Stop();
            Console.WriteLine(x +" - " +(sw.ElapsedMilliseconds).ToString());
        }
    }
Author: Dmitriy Chistyakov, 2017-03-31

1 answers

In C#, I can't say for sure, but in Java-everything looks like this:

  1. The sine is calculated through the System Library. The sources for OpenJDK are here.
  2. To approximate the sine, a polynomial of the 13th degree is used (something like Chebyshev).
  3. In this case, for the values of the argument less than PI/4=0.785, the true sine is calculated.
  4. If the argument is greater than PI/4 is calculated already through the cosine, which is already approximated by a polynomial of the 14th degree, from there the jump to graphics.

Most likely, with C#, the story is similar, only a different library is used.

 14
Author: Barmaley, 2017-04-05 07:56:14