Boost logo

Boost :

From: Sérgio Vale e Pace (svpace.forum_at_[hidden])
Date: 2005-01-27 07:39:11


Jason Hise wrote:
> I was just playing around, trying to compute a square root at compile
> time. I came up with the following:
>
<code snip>
>
> This works for most values, but unfortunately some ( like 80 ) end up
> oscillating and X never becomes equal to X2. How could I go about
> correcting this?

you can do something like this:

template < unsigned int N, unsigned int X = 1, unsigned int X1 = 0,
        unsigned int X2 = ( X + N / X ) / 2 >
struct Sqrt
{
         enum { Value = Sqrt < N, X2, X > :: Value };
};

template < unsigned int N, unsigned int X, unsigned int X1 >
struct Sqrt < N, X, X1, X1 >
{
        enum { Value = X1 };
};

this code takes one more iteration to solve, but avoid the oscillation
problem, I was not sure why you are using this ValueHolder struct so
I took the liberty to remove it, but if you need it, you can bring it
back without any problem.

> -Jason
Sérgio


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk