地图/减少功能编程培训



我想在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)

发生的情况是,在某一点上,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

最新更新