Archived

This topic is now archived and is closed to further replies.

Chris Hare

Compile time sine

Recommended Posts

How can C++ be used to compute sine values for constant arguments, without using macros? That is, how can sin(0.3) be converted to its value as compile time, moved into the instruction? Wizza Wuzza?

Share this post


Link to post
Share on other sites
Granted, but in a long expression, things get messy quickly.

I''d though about using an intermediated template like


template <double x> c_sin
{
public:
const static double val = ... // taylor
};

var = c_sin<0.3>::val // not ideal anyway


but double can''t be a type argument.

I might be able to statically convert the double to some aux class at compile time, i''ll have to look at that.

Wizza Wuzza?

Share this post


Link to post
Share on other sites
What compiler are you using? Depending on how smart your compiler is you can get different ways to do this. For example, on MSVC .NET 2003, you can do

const double sine_of_zero_point_three = sin(0.3);

and it will work happily.

(To be fair, there is a small static initialization overhead, but the actual code using the const variable will be just as efficient as if you used const double sine_of_zero_point_three = 0.29552. If this isn''t good enough, we can talk about the horrors of compile time template metaprogramming.)

Share this post


Link to post
Share on other sites
I cant remember the details but i do remember reading about someone doing a recursive inline function to calculate sin/cos etc, not hot on the maths side of it but i beleive "true sin" is an infinitely long polynomial, once the recursion depth was upped on the compiler the compiler could completely calculate it at compile time

of course you should only use that for constants

Share this post


Link to post
Share on other sites
quote:
Original post by Narcist
of course you should only use that for constants

If its a constant the compiler will probably calculate it at compile time anyway (although if your compiler options are set to something like ''minimum size'' it might leave it to runtime).

Share this post


Link to post
Share on other sites
You write a template function that uses the taylor-series approximation, then you use a meta-template to perform your iteration calling the template taylor-series sin function.

The result is more than just inlined code; the sine values actually become part of the op codes.

I''ve been thinking about writing a meta-template FFT based on this idea...

Share this post


Link to post
Share on other sites