【问题标题】:Training of map/reduce functional programmingmap/reduce函数式编程培训
【发布时间】:2023-03-12 03:25:01
【问题描述】:

我想在 Python 中计算列表中包含的所有数字的对数阶乘,但结果我只得到一个“ValueError:数学域错误”——这是从哪里来的?

from _functools import reduce
import math

nums_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
nums_log_fac = reduce (lambda x, y : (math.log10(x)) + (math.log10(y)), nums_list)
print (nums_log_fac)

【问题讨论】:

  • 这是什么语言?请Edit标记它。

标签: python math lambda reduce factorial


【解决方案1】:

发生的情况是,在某一时刻 math.log10() 被调用一个负值,这会触发域错误。请记住,reduce 的第一遍使用 xy 的可迭代的前两个值(假设没有初始化器)。但是,在每个后续传递中,x 代表上一个 lambda 调用返回的值,y 是迭代中的下一个值。

例子:

from functools import reduce
import math

def do_log10(x, y):
    print(f"x:{x:>5.2f}, y:{y:>5.2f}")
    return math.log10(x) + math.log10(y)

nums_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
nums_log_fac = reduce(do_log10, nums_list)
print (nums_log_fac)

输出:

x: 1.00, y: 2.00
x: 0.30, y: 3.00
x:-0.04, y: 4.00
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-25-2bec9dea93b2> in <module>
      7 
      8 nums_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
----> 9 nums_log_fac = reduce(do_log10, nums_list)
     10 print (nums_log_fac)

<ipython-input-25-2bec9dea93b2> in do_log10(x, y)
      4 def do_log10(x, y):
      5     print(f"x:{x:>5.2f}, y:{y:>5.2f}")
----> 6     return math.log10(x) + math.log10(y)
      7 
      8 nums_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

ValueError: math domain error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多