Python's statistics.geometric_mean in TypeScript

✓ Verified: Python 3.12
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { geometric_mean } from 'locutus/python/statistics/geometric_mean'.

Or with CommonJS: const { geometric_mean } = require('locutus/python/statistics/geometric_mean')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1geometric_mean([54, 24, 36])36.000000000000014
2geometric_mean([1, 3, 9])3
3geometric_mean([2.5, 6.25])3.9528470752104745

Notes

  • Returns the geometric mean for a non-empty dataset of positive numbers.

Dependencies

This function uses the following Locutus functions:

Here's what our current TypeScript equivalent to Python's statistics.geometric_mean looks like.

import { assertStatisticsArray, toStatisticNumber } from '../_helpers/_statistics.ts'

export function geometric_mean(data: unknown): number {
// discuss at: https://locutus.io/python/statistics/geometric_mean/
// parity verified: Python 3.12
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Returns the geometric mean for a non-empty dataset of positive numbers.
// example 1: geometric_mean([54, 24, 36])
// returns 1: 36.000000000000014
// example 2: geometric_mean([1, 3, 9])
// returns 2: 3
// example 3: geometric_mean([2.5, 6.25])
// returns 3: 3.9528470752104745

const values = assertStatisticsArray(data, 'geometric_mean').map((value) =>
toStatisticNumber(value, 'geometric_mean'),
)
if (values.length === 0 || values.some((value) => value <= 0)) {
throw new Error('geometric mean requires a non-empty dataset containing positive numbers')
}

const logSum = values.reduce((sum, value) => sum + Math.log(value), 0)
return Math.exp(logSum / values.length)
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


Help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.

« More Python statistics functions


Star