# Elegant way to transform formula with sum into code

I have this formula, and many other which contains sum, I am perfectly able to do the computation over a list, however to do this I need to do it in several manual steps. Therefore, I wonder if there would be any elegant way of adding sequence to it or hold the expression or something similar making it run without needing to do step wise computation manually.

$$\frac{(x-\bar{x})}{\sum (x-\bar{x})^2}$$

Please note by manually I mean example calculating the mean first and then subtract it from the list and then sum it and so on.

-
Just to be clear, is this what you're trying to simplify? x = Range[10]; y = Mean[x]; (x - y)/Sum[(i - y)^2, {i, x}] – C. E. Sep 29 '13 at 10:11
Yes, that is correct. – ALEXANDER Sep 29 '13 at 10:18
Are you sure you want to divide by the sum? Usually in real applications the mean is divided by the square root of the sum. I know a nice way to do it. – ybeltukov Sep 29 '13 at 16:33
Is the object to define such a quantity without using even the built-in Mean. (That's a reasonable thing to do -- "teaching the computer to do the calculation" -- in order to learn or reinforce learning how such mathematical/statistical things are defined.) – murray Sep 29 '13 at 16:53
Or is the object simply to avoid any explicit use of expressions like Sum[x[[1]], {i,1, n}]? – murray Sep 29 '13 at 17:03

There are number of approaches including:

f[x_List]:=(x-Mean[x])/(Variance[x](Length@x-1))

g[x_List]:=#/Total[#^2]&@(x-Mean[x])

h[x_List]:= #/#.#&@(x-Mean[x])

-

One way to avoid using temporary variables (avoiding duplication of code is the cause of having to use several steps) is to write an anonymous function.

(# - #2)/Sum[(i - #2)^2, {i, #}] &[x, Mean[x]]


But doing things in several steps isn't always wrong, it can make the code much more readable. One just has to remember to use Module so one doesn't pollute the name space and cause strange errors later on in the same session.

In the above code, [x,Mean[x]] has a duplicate x in it. If you only have x as an expression you don't want to substitute it in at two places, so you can do this:

(# - #2)/Sum[(i - #2)^2, {i, #}] &[#, Mean[#]] &[Range[10]]

-
This is great, gives me an idea of how to go on about solving other formulas that contain sum. – ALEXANDER Sep 29 '13 at 10:34
Why do you not want to substitute it in at two places? – ALEXANDER Sep 29 '13 at 10:36
@ALEXANDER Any duplication of code is not considered very good. Especially if it's computationally expensive. If x is, say, Permutations[Range[10]] (not cheap to compute) [x,Mean[x]] will compute it twice but [#,Mean[#]]&[x] will only compute it once. – C. E. Sep 29 '13 at 10:38
And when I write x, I don't mean that you've previously executed x=Permutations[Range[10]]. I mean that you substitute Permutations[Range[10]] everywhere it says x. – C. E. Sep 29 '13 at 10:42
Great thank you! – ALEXANDER Sep 29 '13 at 22:18