快速高效计算sin与cos
生活随笔
收集整理的這篇文章主要介紹了
快速高效计算sin与cos
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
為什么80%的碼農都做不了架構師?>>> ??
將[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; } }轉載于:https://my.oschina.net/foohao/blog/685721
總結
以上是生活随笔為你收集整理的快速高效计算sin与cos的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: protocol_buffers简易操作
- 下一篇: 认识微信公众号