Nth root of a small number returns unexpected result in C #

When I try to take the Nth root of a small number using C #, I get the wrong number.

For example, when I try to take the third root of 1.07, I get 1, which is clearly wrong.

Here is the exact code that I use to get the third root.

MessageBox.Show(Math.Pow(1.07,(1/3)).toString());

How to solve this problem?

I would suggest that this is a floating point arithmetic problem, but I don't know how to handle it.

+5
source share
4 answers

I am sure that the "exact code" you give is not compiling.

MessageBox.Show(Math.Pow(1.07,(1/3).toString()));

toString , ToString, (1/3) , , , , . (1/3) 0, 1. (1.0/3.0) (1d/3d) ...

+9

# 1 3 , :

Math.Pow(1.07,(1d/3d))

Math.Pow(1.07,(1.0/3.0))

, .

+13

: , , - : -)

MessageBox.Show(Math.Pow(1.07,(1/3).toString()));

(1/3).toString(), 1.07 .

, :

MessageBox.Show(Math.Pow(1.07,(1/3)).ToString());

, (1/3) , 0, n 0 1 n.

You need to make it float something like 1.0/3.0.

+3
source

This may help if you have a real problem with the nth root error, but my experience is that the built-in Math.Pow (double, int) is more accurate:

    private static decimal NthRoot(decimal baseValue, int N)
    {
        if (N == 1)
            return baseValue;
        decimal deltaX;
        decimal x = 1M;
        do
        {
            deltaX = (baseValue / Pow(x, N - 1) - x) / N;
            x = x + deltaX;
        } while (Math.Abs(deltaX) > 0);
        return x;
    }

    private static decimal Pow(decimal a, int b)
    {
        if (b == 0) return 1;
        if (a == 0) return 0;
        if (b == 1) return a;
        if (b % 2 == 0)
            return Pow(a * a, b / 2);
        else if (b % 2 == 1)
            return a * Pow(a * a, b / 2);
        return 0;
    }
+1
source

All Articles