While writing a program I came across finding the cube root of a number in one of my functions.
when I used the below code, I was getting an incorrect value for the
The error (which, by the way, is just 4E-16
- 400 quintillionths) is caused by floating point errors.
You could circumvent this by rounding the number if it is within a certain threshold:
public static void cubicPairs(double n)
{
double root = (System.Math.Pow(n, (1/3)));
double roundedRoot = Math.Round(root);
if (Math.Abs(roundedRoot - root) < VERY_SMALL_NUMBER)
return roundedRoot;
else
return root;
}
Where VERY_SMALL_NUMBER
can be, say, 1e-10
.