Skip to content

Instantly share code, notes, and snippets.

@mao-test-h
Last active August 1, 2018 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mao-test-h/ea6ce9de3a1ac350c7daf002dc3159f7 to your computer and use it in GitHub Desktop.
Save mao-test-h/ea6ce9de3a1ac350c7daf002dc3159f7 to your computer and use it in GitHub Desktop.
級数展開でcosの近似値を出すテスト
// https://twitter.com/TEST_H_/status/1023975602494169092
using System;
using System.Diagnostics;
namespace MyContents
{
class Test
{
static void Main()
{
Stopwatch sw = new Stopwatch();
sw.Start();
for(int i = 0; i < 360; ++i)
{
float rad = i * ((3.14f * 2) / 360f);
#if false
float ret = 1 - (Pow(rad, 2) / 2)
+ (Pow(rad, 4) / Factorial(4))
- (Pow(rad, 6) / Factorial(6))
+ (Pow(rad, 8) / Factorial(8));
#else
// 高速版
float pow1 = rad * rad;
float pow2 = pow1 * pow1;
float pow3 = pow2 * pow1;
float pow4 = pow2 * pow2;
float ret = 1 - (pow1 / 2f)
+ (pow2 / 24f) // 4!
- (pow3 / 720f) // 6!
+ (pow4 / 40320f); // 8!
#endif
Console.WriteLine(ret);
}
sw.Stop();
Console.WriteLine("Elapsed = {0}", sw.Elapsed);
}
static float Pow(float x, float y)
{
return (float)Math.Pow((double)x, (double)y);
}
static int Factorial(int n)
{
int x = 1;
while(n > 1)
{
x = x * n;
n--;
}
return x;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment