6
$\begingroup$

I have the following datas: fg I want to find mean age by using following formula, f

Any way to do this in general in Mathematica easily.

$\endgroup$
  • 4
    $\begingroup$ I was under the impression that SE can handle Latex(?) directly, why use a (blurry for me) image? $\endgroup$ – CGCampbell Oct 14 at 12:59
  • $\begingroup$ I turned mean at around five and a half. So that's one data point. $\endgroup$ – Daniel Lichtblau Oct 14 at 13:29
12
$\begingroup$

You need EmpiricalDistribution:

data = {14, 15, 16, 22, 24, 25};
weights = {1, 1, 3, 2, 2, 5};

\[ScriptCapitalD] = EmpiricalDistribution[weights -> data];

Expectation[x, x \[Distributed] \[ScriptCapitalD]]
(* 21 *)
| improve this answer | |
$\endgroup$
  • 2
    $\begingroup$ To the downvoter, I am interested in what's wrong with my answer, would you please elaborate. I'm not trying to complain here, I just want to improve my answer if possible. $\endgroup$ – xzczd Oct 14 at 12:13
10
$\begingroup$
values = {14, 15, 16, 22, 24, 25};
weights = {1, 1, 3, 2, 2, 5};

You can also use WeightedData:

Mean @ WeightedData[values, weights]
21

or use Mean with EmpiricalDistribution:

Mean @ EmpiricalDistribution[weights -> values]
21

Both methods also work with symbolic input:

values = Array[Subscript[x, #] &, 5];
weights = Array[Subscript[w, #] &, 5];

Mean @ WeightedData[values, weights] 

enter image description here

TeXForm @ %

$$\frac{w_1 x_1+w_2 x_2+w_3 x_3+w_4 x_4+w_5 x_5}{w_1+w_2+w_3+w_4+w_5}$$

Mean @ EmpiricalDistribution[weights -> values] // Together // TeXForm

$$\frac{w_1 x_1+w_2 x_2+w_3 x_3+w_4 x_4+w_5 x_5}{w_1+w_2+w_3+w_4+w_5}$$

| improve this answer | |
$\endgroup$
4
$\begingroup$

These are all quite fancy solutions so far. For beginners' sake, I'd like to add a somewhat more elementary one that uses somewhat more universal tools:

ages = {14, 15, 16, 22, 24, 25};
counts = {1, 1, 3, 2, 2, 5};

ages.counts/Total[counts]

21

The . (a.k.a. Dot) computes this sum

Sum[ages[[i]] counts[[i]], {i, 1, Length[ages]}]

and Total computes this one:

Sum[counts[[i]], {i, 1, Length[ages]}]

So one can also obtain the result as follows:

Sum[ages[[i]] counts[[i]], {i, 1, Length[ages]}]/Sum[counts[[i]], {i, 1, Length[counts]}]

But Dot and Total are typically faster because they rely on very optimized libraries in the background. And of course, it is also shorter to type.

| improve this answer | |
$\endgroup$
  • $\begingroup$ @xzczd Oops. Indeed, I copy-pasted from everywhere! Thank you for pointing me to it! $\endgroup$ – Henrik Schumacher Oct 14 at 7:13
3
$\begingroup$

Using your formula

Clear["Global`*"]

ages = {14, 15, 16, 22, 24, 25};

counts = {1, 1, 3, 2, 2, 5};

Evaluate[n /@ ages] = counts;

?n

enter image description here

mean = Sum[j*n[j], {j, ages}]/Total[counts]

(* 21 *)
| improve this answer | |
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.