Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'd probably check it like this, because my policy is to be paranoid about the accuracy of math functions:</p> <pre><code>double root = sqrt(z); int introot = floor(root + 0.5); // round to nearby integer if ((introot * introot) == z) { // integer arithmetic, so precise cout &lt;&lt; introot &lt;&lt; " == sqrt(" &lt;&lt; z &lt;&lt; ")\n"; } </code></pre> <p><code>double</code> can exactly represent all the integers we care about (for that matter, on most implementations it can exactly represent all the values of <code>int</code>). It also has enough precision to distinguish between <code>sqrt(x)</code> and <code>sqrt(x+1)</code> for all the integers we care about. sqrt(10000) - sqrt(9999) is 0.005, so we only need 5 decimal places of accuracy to avoid false positives, because a non-integer square root can't be any closer than that to an integer. A good <code>sqrt</code> implementation therefore can be accurate enough that <code>(int)root == root</code> on its own would do the job.</p> <p>However, the standard doesn't specify the accuracy of <code>sqrt</code> and other math functions. In C99 this is explicitly stated in 5.2.4.2.2/5: I'm not sure whether C89 or C++ make it explicit. So I'm reluctant to rule out that the result could be out by a ulp or so. <code>int(root) == root</code> would give a false negative if <code>sqrt(7744)</code> came out as 87.9999999999999-ish</p> <p>Also, there are much larger numbers where <code>sqrt</code> can't be exact (around the limit of what <code>double</code> can represent exactly). So I think it's easier to write the extra two lines of code than to write the comment explaining why I think math functions will be exact in the case I care about :-)</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. 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