Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For big X values (around 700 and above), you'll hit the range limit for doubles (10^308) and cause an infinite loop. You can't do much about it, you should either limit X input range or use some big number library to have extended range. </p> <p>Another workaround is to add this to your loop:</p> <pre><code>if (sum &gt; 1E305) { // we'll most likely run into an infinite loop break; } </code></pre> <p>Note you should handle this case outside the loop afterwards to avoid printing a very large incorrect result.</p> <p>I can't reproduce the problem for <code>0.00000000001</code>, this just returns 1 for me. Negative values run fine, too, although the result is wrong which seems to be an error/limitation in the algorithm. EDIT: To correct this, we can use the fact that <code>e^-x</code> is the same as <code>1 / e^x</code>.</p> <p>Code:</p> <pre><code>#include &lt;stdio.h&gt; double CalcExp(double x){ double eps = 0.0000000000000000001; double elem = 1.0; double sum = 0.0; bool negative = false; int i = 1; sum = 0.0; if (x &lt; 0) { negative = true; x = -x; } do { sum += elem; elem *= x / i; i++; if (sum &gt; 1E305) break; } while (elem &gt;= eps); if (sum &gt; 1E305) { // TODO: Handle large input case here } if (negative) { return 1.0 / sum; } else { return sum; } } int main() { printf("%e\n", CalcExp(0.00000000001)); // Output: 1.000000e+000 printf("%e\n", CalcExp(-4)); // Output: 1.831564e-002 printf("%e\n", CalcExp(-45)); // Output: 2.862519e-020 printf("%e\n", CalcExp(1)); // Output: 2.718282e+000 printf("%e\n", CalcExp(750)); // Output: 1.375604e+305 printf("%e\n", CalcExp(7500000)); // Output: 1.058503e+305 printf("%e\n", CalcExp(-450000)); // Output: 9.241336e-308 return 0; } </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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