我可以用 django 注释计算几何平均值吗?
Can I calculate the geometric mean with django annotation?
有没有办法像
Foo.objects.annotate(geometric_mean=GeometricMean('bars__value'))
或
Foo.objects.annotate(geometric_mean=Power(Prod('bars__value'), Count('bars'))
你可以做一些非常相似的事情:你可以计算自然对数的平均值:
from django.db.models import Avg
from django.db.models.functions import Ln
Foo.objects.annotate(geometric_mean=<b>Avg(Ln('bars__value'))</b>)
那么几何平均数就是这个的指数。如果您真的需要几何平均值本身,那么您可以对该结果使用 Exp
[Django-doc]:
from django.db.models import Avg
from django.db.models.functions import Exp, Ln
Foo.objects.annotate(geometric_mean=<b>Exp(Avg(Ln('bars__value')))</b>)
但是如果您只想通过两个几何平均值 order 则不需要这个,因为指数保持顺序关系不变:ea≤eb 意味着 a≤b 反之亦然。
这是有效的,因为 ln(x1×x2×…×xn ) 等价于 ln(x1)+ln(x2) +…+ln(xn) 和 ln(xy)等价于 y×ln(x).
有没有办法像
Foo.objects.annotate(geometric_mean=GeometricMean('bars__value'))
或
Foo.objects.annotate(geometric_mean=Power(Prod('bars__value'), Count('bars'))
你可以做一些非常相似的事情:你可以计算自然对数的平均值:
from django.db.models import Avg
from django.db.models.functions import Ln
Foo.objects.annotate(geometric_mean=<b>Avg(Ln('bars__value'))</b>)
那么几何平均数就是这个的指数。如果您真的需要几何平均值本身,那么您可以对该结果使用 Exp
[Django-doc]:
from django.db.models import Avg
from django.db.models.functions import Exp, Ln
Foo.objects.annotate(geometric_mean=<b>Exp(Avg(Ln('bars__value')))</b>)
但是如果您只想通过两个几何平均值 order 则不需要这个,因为指数保持顺序关系不变:ea≤eb 意味着 a≤b 反之亦然。
这是有效的,因为 ln(x1×x2×…×xn ) 等价于 ln(x1)+ln(x2) +…+ln(xn) 和 ln(xy)等价于 y×ln(x).