第n个根实现 [英] nth root implementation

查看:126
本文介绍了第n个根实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究计算数字的n th 根的方法。但是,我遇到负数的第n个 th 根问题。

I am working on a way to calculate the nth root of a number. However, I am having problems with the nth root of negative numbers.

大多数人都说使用数学。 pow(num,1 / root),但这不适用于负数。

Most people say to use Math.pow(num, 1 / root), but this does not work for negative numbers.

我试过这个:

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

但是,它不适用于所有数字,因为根可以是小数。例如 root(-26,0.8)返回 -58.71 ,但这是无效输入。即使是根也会给出错误的答案。例如 root(-2,2)返回 -1.41421 ,但-2没有平方根。

but, it does not work for all numbers as the root can be a decimal. For example root(-26, 0.8) returns -58.71, but that is an invalid input. This will also give the wrong answer for even roots. For example root(-2, 2) returns -1.41421, but -2 does not have a square root.

推荐答案

你想做什么?除非你计划完全正确处理复数,否则你不能取负数的第n个根。

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.

例如,当( - 8)^(1/3)的主分支 -2 的唯一分支( - 4) ^(1/2) 2i -2i

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.

所以 -8 是复数 8 * exp(i * pi) 1/3 的根是 2 * exp(i * pi / 3) 2 * exp(i * pi) 2 * exp [i *( - pi)/ 3] 。然后,您可以使用 de Moivre'公式来计算<$ c $格式的根c> a + bi 。

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.

这篇关于第n个根实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆