FloatingPoint

From C

Jump to: navigation, search

Recipes

This page collects answers to frequently asked questions on FP arithmetic.

Squares, cubes

An often asked question is how to test whether a number is full square (cube, etc). Instead of testing whether sqrt(n) is integer (sqrt(n)==rint(sqrt(n)), a better approach is: calculate s = rint(sqrt(n)) and check that s*s == n. (s should be integer variable). The equality test in the latter expression is exact since it is integer comparison. This approach is more reliable approach due to rounding errors.

The rint function returns the nearest integer (as sqrt can both undershoot and overshoot the true sqrt value).

Personal tools