我正在构建一个快速的三角函数近似在一个单一的头文件。
#ifndef COOL_MATH_H
#define COOL_MATH_H
#include <cmath>
const float PI = std::acos(-1);
namespace trigonometry
{
namespace
{
float _cos[180];
}
void init()
{
for (int i = 0; i < 90; i++)
{
_cos[i] = cosf(float(i) * PI/180.0f);
}
}
float cos(float deg)
{
int nearest = int(abs(deg) + 0.5) % 90;
return _cos[nearest];
}
float sin(float deg)
{
return cos(90.0f - deg);
}
}
#endif如果我错了,纠正我,但是理论上这个近似比内置的trig函数更快?
主要问题是:如果包含了头文件(即只包含一次),我如何运行函数trigonometry::init()?我只想存储_cos[180]的值一次。
发布于 2021-05-12 16:40:50
当头文件被包含时,
如何运行函数三角函数::init()(即只包含一次)?
#ifndef COOL_MATH_H
#define COOL_MATH_H
#include <cmath>
#include <array>
const float PI = std::acos(-1);
namespace trigonometry
{
namespace
{
std::array<float, 180> init()
{
std::array<float, 180> cos;
for (int i = 0; i < 90; i++)
{
cos[i] = cosf(float(i) * PI/180.0f);
}
return cos;
}
std::array<float, 180> _cos = init();
}
float cos(float deg)
{
int nearest = int(abs(deg) + 0.5) % 90;
return _cos[nearest];
}
float sin(float deg)
{
return cos(90.0f - deg);
}
}
#endif注意,每个翻译单元,包括您的cool_math.h,都有自己的数组、float _cos[180]和弱函数。要在所有翻译单元之间共享唯一的float _cos[180],您需要将数组和函数定义移动到cool_math.cc,或者将它们声明为某个类的静态成员,并在cool_math.cc中定义float _cos[180]。
https://stackoverflow.com/questions/67507494
复制相似问题