Skip to main content
 首页 » 编程设计

python几何平均数计算

2024年09月07日58lautakyan007

如何在没有 numpy 的情况下用 Python 以安全的方式计算数字列表的几何平均值,所以我确实避免了此函数有时会产生的 RuntimeWarning:

data = [1,2,3,4,5] 
result = reduce(mul, data) ** (1 / len(data)) 

我发现我可以使用这个日志函数来获得相同的结果,但是我对日志函数不接受负值有疑问。

result = (1 / len(data)) * sum(list(map(math.log10, data))) 

我可以把map前用abs函数映射到log10的数据吗? 有更好的方法吗?

请您参考如下方法:

一般负数的n次方根都是复数

该代码适用于 cmath base e log, exponentiation

from functools import reduce 
import operator 
from cmath import log, e 
 
data = [1,2,3,4,5] 
 
rmul = reduce(operator.mul, data) ** (1 / len(data)) 
 
rln = e**((1 / len(data)) * sum(list(map(log, data)))) 
 
rmul, rln 
Out[95]: (2.605171084697352, (2.6051710846973517+0j)) 
 
data = [1,2,3,-4,5] 
 
rmul = reduce(operator.mul, data) ** (1 / len(data)) 
 
rln = e**((1 / len(data)) * sum(list(map(log, data)))) 
 
rmul, rln 
Out[96]:  
((2.1076276807743737+1.531281143283889j), 
 (2.1076276807743732+1.5312811432838889j)) 

一些检查:

abs(rln) 
Out[97]: 2.6051710846973517 
 
rln**5 
Out[98]: (-120.00000000000003-1.4210854715202004e-14j) 

为了更多的乐趣和争论:

正值 a 的“the”平方根不是单数,而是正数,它是 + 和 - 符号值:+/- sqrt(a)

和负 a 的“the”平方根同样是 +/- 1j * sqrt(a) 值