[Tutor] How to handle exceptions raised inside a function?
steve at pearwood.info
Wed Dec 1 23:11:17 CET 2010
Richard D. Moores wrote:
>> def harmonic_mean(data):
>> m = mean(1.0/x for x in data)
>> except ZeroDivisionError:
>> return 0.0
>> if m == 0.0:
>> return math.copysign(float('inf'), m)
>> return 1/m
> math.copysign! Didn't know about that one. But "mean"? It's not a
> built-in function..
No, it's not, it's a function from my stats module.
The naive version is simple:
My version is a bit more complicated than that, in order to minimize
round-off error and support iterators.
More information about the Tutor