I wonder is there any easy way to do geometric mean using python but without using python package. If there is not, is there any simple package to do geometric mean?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Geometric mean
Geometric mean with Scipy
The formula of the gemetric mean is:
So you can easily write an algorithm like:
You do not have to use numpy for that, but it tends to perform operations on arrays faster than Python (since there is less "overhead" with casting).
In case the chances of overflow are high, you can map the numbers to a log domain first, calculate the sum of these logs, then multiply by 1/n and finally calculate the exponent, like:
Here's an overflow-resistant version in pure Python, basically the same as the accepted answer.
In case someone is looking here for a library implementation, there is gmean() in scipy, possibly faster and numerically more stable than a custom implementation:
just do this:
You can also calculate the geometrical mean with numpy:
result: