Hi,
I have a piece of code which I think should be working, but it doesn't.
def standard_dev(a, mean)
Math.sqrt((a.inject(0.0){|v,r| r += (v-mean)*(v-mean) })/a.length)
end
computes results that don't make sense and differ from the values computed by this code:
def standard_dev(a, mean)
r = 0.0
a.each{|v| r += (v-mean)*(v-mean) }
Math.sqrt(r/a.length)
end
I think the two should be different. Am I missing something?
-- stefan
Stefan Kaes wrote:
Hi,
I have a piece of code which I think should be working, but it doesn't.
def standard_dev(a, mean)
Math.sqrt((a.inject(0.0){|v,r| r += (v-mean)*(v-mean) })/a.length)
end
computes results that don't make sense and differ from the values computed by this code:
def standard_dev(a, mean)
r = 0.0
a.each{|v| r += (v-mean)*(v-mean) }
Math.sqrt(r/a.length)
end
Oops. This should have been:
···
I think the two should be *identical*. Am I missing something?
Stefan Kaes a écrit :
Hi,
I have a piece of code which I think should be working, but it doesn't.
def standard_dev(a, mean)
Math.sqrt((a.inject(0.0){|v,r| r += (v-mean)*(v-mean) })/a.length)
end
Well, try this :
def standard_dev(a, mean)
Math.sqrt((a.inject(0.0){|r,v| r += (v-mean)*(v-mean) })/a.length)
end
....
The doc says:
enum.inject {| memo, obj | block } => obj
You just swapped the two arguments ...
Pierre
···
computes results that don't make sense and differ from the values
computed by this code:
def standard_dev(a, mean)
r = 0.0
a.each{|v| r += (v-mean)*(v-mean) }
Math.sqrt(r/a.length)
end
I think the two should be different. Am I missing something?
-- stefan
Pierre Barbier de Reuille wrote:
The doc says:
enum.inject {| memo, obj | block } => obj
You just swapped the two arguments ...
Pierre
Dang. I copied this from code for computing the average, which is insensitive to block argument order. Thanks.