快速高效计算sin与cos

将[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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值