possible bug?

S

Stefan Kaes

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
 
S

Stefan Kaes

Stefan said:
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:
 
P

Pierre Barbier de Reuille

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
 
S

Stefan Kaes

Pierre said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,183
Messages
2,570,966
Members
47,513
Latest member
JeremyLabo

Latest Threads

Top