将[0, 90)度的cos值采取一定的精确度寸储起来,下次使用时直接取出值,精确到0.0001°的话,需占用3MB+的空间。
#include <fstream>
#include <cmath>
#include <thread>
using namespace std;
float math::sin(float angle)
{
return cos(angle - 90);
}
float math::cos(float angle)
{
const int precision = 10000; // 保存到0.0001
const int cacheSize = 90 * precision;
static float cosCache[cacheSize] = {0};
if (cosCache[0] == 0) // load cache if havn't initialize the data
{
static bool loading = false;
const double pi = 3.1415926535898;
if (!loading)
{
loading = true;
thread([&cosCache,pi]()mutable{
fstream file("cos.dat", std::ios_base::in|std::ios_base::binary);
if (file)
{
file.read((char*)cosCache, sizeof(cosCache));
file.close();
}
else
{
file.close();
for (int i = 0; i < cacheSize; ++i)
{
cosCache[i] = static_cast<float>(std::cos(i * pi / 180 / precision));
}
file.open("cos.dat", std::ios_base::out|std::ios_base::binary);
file.write((char*)cosCache, sizeof(cosCache));
file.close();
}
}).detach();
}
return std::cos(angle * pi / 180);
}
int angleE4 = int(round(abs(angle) * 1e4)) % (360*precision);
switch (angleE4 / cacheSize) {
case 0:
return cosCache[angleE4];
case 1:
angleE4 -= cacheSize;
if (90*precision == cacheSize - angleE4)
return 0;
return -cosCache[cacheSize - angleE4];
case 2:
return -cosCache[angleE4 % cacheSize];
case 3:
angleE4 %= cacheSize;
if (90*precision == cacheSize - angleE4)
return 0;
return cosCache[cacheSize - angleE4];
default:
return 0;
}
}