【问题标题】:error inputting array element into recursive function将数组元素输入递归函数时出错
【发布时间】:2020-02-04 06:10:15
【问题描述】:

我试图将一个数组元素传递给一个递归函数,该函数计算阶乘并输出 0。有一条警告说 long_scalars 中遇到了溢出。每当我将硬编码数字传递给函数时,它似乎都可以正常工作。有谁知道为什么会发生这种情况或如何解决?

rand_10 = np.random.randint(100,500,10)

数组([173, 171, 375, 432, 393, 334, 268, 341, 183, 270])

def fact(x):
  if x == 1:
    return 1
  else:
    return x * fact(x-1)

fact(rand_10[0])

RuntimeWarning:long_scalars 中遇到溢出

输出: 0

编辑:我阅读了可能重复中提供的链接。我仍然无法弄清楚如何解决这个问题。如果这是解决方案,我应该如何以及在哪里将 dtype 设置为 int64?

【问题讨论】:

标签: python


【解决方案1】:

这是工作代码:

import numpy as np

rand_10 = np.random.randint(100,500,10, dtype=np.int64)

def fact(x):
    if x == 1:
        return 1
    else:
        return x * fact(x-1)

x = rand_10[0].item()   # method item() to convert the value into a native Python type
print(fact(x))

rand_10[0] 返回类型 numpy.int64。因此,您需要使用方法 item() 将其转换为原生 Python 类型(即 int) >

最好的问候!

【讨论】:

    猜你喜欢
    • 2020-03-15
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多