You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何求一个数的指定次方根?含双参数函数实现需求

计算指定数字的n次根的函数实现

核心逻辑

计算数字的n次根,本质是求该数字的1/n次方,通过幂运算即可完成。同时需要处理两类无效输入:非正的根次数、负数的偶次根(实数范围内无意义)。

Python 实现示例

def calculate_nth_root(number, root_degree):
    if root_degree <= 0:
        raise ValueError("根次数必须是正整数")
    if number < 0 and root_degree % 2 == 0:
        raise ValueError("负数的偶次根在实数范围内不存在")
    return number ** (1 / root_degree)

调用示例

计算4的五次根:

result = calculate_nth_root(4, 5)
print(result)  # 输出约 1.3195079107728942

JavaScript 实现示例

function calculateNthRoot(number, rootDegree) {
    if (rootDegree <= 0) {
        throw new Error("根次数必须是正整数");
    }
    if (number < 0 && rootDegree % 2 === 0) {
        throw new Error("负数的偶次根在实数范围内不存在");
    }
    return Math.pow(number, 1 / rootDegree);
}

调用示例

计算4的五次根:

const result = calculateNthRoot(4, 5);
console.log(result);  // 输出约 1.3195079107728942

内容的提问来源于stack exchange,提问作者Younes Vesey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 03:20:05