Created
March 8, 2020 02:15
-
-
Save beru/aabaea2840a50d1d3c0eca7806cb2558 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <cmath> | |
#define PI 3.14159265358979323846f | |
#define DEG2PI (PI / 180.0f) | |
#define PI2DEG (180.0f / PI) | |
#define EXTRA_PRECISION | |
#if 0 | |
// https://stackoverflow.com/questions/2683588/what-is-the-fastest-way-to-compute-sin-and-cos-together/2683853#2683853 | |
float sine(float x) | |
{ | |
if (x > PI) | |
x -= 2 * PI; | |
const float B = 4 / PI; | |
const float C = -4 / (PI * PI); | |
float y = B * x + C * x * std::abs(x); | |
#ifdef EXTRA_PRECISION | |
// const float Q = 0.775; | |
const float P = 0.225; | |
y = P * (y * abs(y) - y) + y; // Q * y + P * y * abs(y) | |
#endif | |
return y; | |
} | |
float cosine(float x) | |
{ | |
x += PI/2; | |
return sine(x); | |
} | |
#else | |
// https://stackoverflow.com/a/53113880 | |
// https://www.codeproject.com/Tips/700780/Fast-floor-ceiling-functions | |
template <typename T> | |
T myfloor(T x) | |
{ | |
return (int)(x + 32768.) - 32768; | |
} | |
// https://stackoverflow.com/a/28050328 | |
template<typename T> | |
T cosine(T x) | |
{ | |
constexpr T tp = 1./(2.*PI); | |
x *= tp; | |
x -= T(.25) + myfloor(x + T(.25)); | |
x *= T(16.) * (std::abs(x) - T(.5)); | |
#ifdef EXTRA_PRECISION | |
x += T(.225) * x * (std::abs(x) - T(1.)); | |
#endif | |
return x; | |
} | |
template<typename T> | |
T sine(T x) | |
{ | |
return cosine(x - PI/2); | |
} | |
#endif | |
int main(int argc, char* argv[]) | |
{ | |
std::FILE* f = std::fopen("test.csv", "w"); | |
for (int i=0; i<360; i += 4) { | |
float rad = i * DEG2PI; | |
#if 0 | |
float x = std::sinf(rad); | |
float y = std::cosf(rad); | |
#else | |
float x = sine(rad); | |
float y = cosine(rad); | |
#endif | |
std::fprintf(f, "%.5f,%.5f\n", x, y); | |
} | |
std::fclose(f); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment