Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The binary splitting method lends itself nicely to a template metaprogram which produces a type which represents a rational corresponding to an approximation of e. 13 iterations seems to be the maximum - any higher will produce a "integral constant overflow" error.</p> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; template&lt;int NUMER = 0, int DENOM = 1&gt; struct Rational { enum {NUMERATOR = NUMER}; enum {DENOMINATOR = DENOM}; static double value; }; template&lt;int NUMER, int DENOM&gt; double Rational&lt;NUMER, DENOM&gt;::value = static_cast&lt;double&gt; (NUMER) / DENOM; template&lt;int ITERS, class APPROX = Rational&lt;2, 1&gt;, int I = 2&gt; struct CalcE { typedef Rational&lt;APPROX::NUMERATOR * I + 1, APPROX::DENOMINATOR * I&gt; NewApprox; typedef typename CalcE&lt;ITERS, NewApprox, I + 1&gt;::Result Result; }; template&lt;int ITERS, class APPROX&gt; struct CalcE&lt;ITERS, APPROX, ITERS&gt; { typedef APPROX Result; }; int test (int argc, char* argv[]) { std::cout &lt;&lt; std::setprecision (9); // ExpType is the type containing our approximation to e. typedef CalcE&lt;13&gt;::Result ExpType; // Call result() to produce the double value. std::cout &lt;&lt; "e ~ " &lt;&lt; ExpType::value &lt;&lt; std::endl; return 0; } </code></pre> <p>Another (non-metaprogram) templated variation will, at compile-time, calculate a double approximating e. This one doesn't have the limit on the number of iterations.</p> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; template&lt;int ITERS, long long NUMERATOR = 2, long long DENOMINATOR = 1, int I = 2&gt; struct CalcE { static double result () { return CalcE&lt;ITERS, NUMERATOR * I + 1, DENOMINATOR * I, I + 1&gt;::result (); } }; template&lt;int ITERS, long long NUMERATOR, long long DENOMINATOR&gt; struct CalcE&lt;ITERS, NUMERATOR, DENOMINATOR, ITERS&gt; { static double result () { return (double)NUMERATOR / DENOMINATOR; } }; int main (int argc, char* argv[]) { std::cout &lt;&lt; std::setprecision (16); std::cout &lt;&lt; "e ~ " &lt;&lt; CalcE&lt;16&gt;::result () &lt;&lt; std::endl; return 0; } </code></pre> <p>In an optimised build the expression <code>CalcE&lt;16&gt;::result ()</code> will be replaced by the actual double value.</p> <p>Both are arguably quite efficient since they calculate e at compile time :-)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload