Cos, Sin, Tan. Trigonometric functions are available in .NET. We test them for correctness. They are found in the Math type in the System namespace.
We examine the Acos, Cos, Cosh, Asin, Sin, Sinh, Atan, Tan and Tanh methods. For an optimization, we can sometimes use a switch-statement with precomputed values.
To begin, we present a program that simply calls Acos, Cos, Cosh, Asin, Sin, Sinh, Atan, Tan and Tanh. All of these methods receive arguments in units of radians represented by the double type.
using System;
using System.Diagnostics;
class Program
{
/// <summary>
/// Optimized version of Sin.
/// </summary>
static double SinFast(int value)
{
switch (value)
{
case 0:
return 0;
case 1:
return 0.841470984807897;
case 2:
return 0.909297426825682;
case 3:
return 0.141120008059867;
case 4:
return -0.756802495307928;
case 5:
return -0.958924274663138;
case 6:
return -0.279415498198926;
case 7:
return 0.656986598718789;
case 8:
return 0.989358246623382;
case 9:
return 0.412118485241757;
default:
return Math.Sin(value);
}
}
const int _max = 1000000;
static void Main()
{
var s1 = Stopwatch.StartNew();
// Version 1: use Math.sin.for (int i = 0; i < _max; i++)
{
for (int a = 0; a < 10; a++)
{
double v = Math.Sin(a);
if (v == -1)
{
throw new Exception();
}
}
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use SinFast.for (int i = 0; i < _max; i++)
{
for (int a = 0; a < 10; a++)
{
double v = Program.SinFast(a);
if (v == -1)
{
throw new Exception();
}
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));
}
}301.76 ns 35.82 ns
A summary. We can apply the standard trigonometric methods, including Acos, Cos, Cosh, Asin, Sin, Sinh, Atan, Tan, and Tanh from .NET.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 6, 2022 (simplify).