nth root implementation

社会主义新天地 提交于 2019-11-30 08:24:39

What are you trying to do? Unless you're planning to fully and properly handle complex numbers you cannot take the nth root of a negative number.

For example, while (-8)^(1/3) has a principal branch of -2, the only branches of (-4)^(1/2) are 2i and -2i.

To handle this properly you need to transform the number into its polar form and then take the required root in that form.

So -8 is the complex number 8*exp(i*pi). The 1/3 roots of that are 2*exp(i*pi/3), 2*exp(i*pi), and 2*exp[i*(-pi)/3]. Then you can use de Moivre' formula to compute the roots in the form a + bi.

(num) ^ (1/root) is similar to exp( (1/root) * log(num) ), so you can do it like:

public static double root(double num, double root)
{
    return Math.pow(Math.E, Math.log(num)/root);
} 

Either use one of the many complex number packages available on the Internet, or convert your number to a rectangular position on the Argand plane, rotate it the appropriate angle as given by the root, then read it out as a (real, imaginary) pair.

I use the method below. Maybe it's not the most accurate, but it works well in my case.

public double root(double num, double root) {
    double d = Math.pow(num, 1.0 / root);
    long rounded = Math.round(d);
    return Math.abs(rounded - d) < 0.00000000000001 ? rounded : d;
}

You could do if(num < 0){ return Math.abs(Math.pow(num, 1 / root)) } Then just use ' + "i"' whenever stating the value. Or use the absolute value for equations and later factor in the positive/negative and i when needed. That's what worked for me.

Alexis Labat
    public double root(double num, double root) {
        double y=1;
        double x;
        while(Math.pow(x, root) != num) {
            if(Math.pow(x, root) > num) {
                x=x-y;
                y=y/10;
            } else {
                x=x+y;
            }
        }
        return x;
    }   

This should work fine for you, although it isn't compact it uses as little math functions as possible.

I'm not too sure about the exact code, but add an extra if statement to clarify between odd and even roots. something along the lines of

public static double root(double num, double root) {
    if (num < 0) {
        if(root%2==1) {
            return -Math.pow(Math.abs(num), (1 / root));
        }
    }
    return Math.pow(num, 1.0 / root);
}

Not entirely sure if this will work with your other code, but I hope it can help

System.out.println( Math.pow(10, Math.log10(Number)/root));

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!