Find Cube root of a number Using System.Math.Pow() method in C#

前端 未结 5 998
面向向阳花
面向向阳花 2020-12-18 05:10

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

5条回答
  •  温柔的废话
    2020-12-18 05:54

    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.

提交回复
热议问题