Reputation: 247
here is the code: when calculate, something error:
arr = [0.054954087385762455, 0.5093998626512432, 5.880466289995431, 0.8639141517665208, 0.2152490168404071]
sum = arr.inject {|sum, item| sum + item}
tmp = 0
arr.each do |pwr|
tmp = tmp + (pwr / sum - 0.2) ** 2
end
puts tmp # 0.42948006253339877
pp ( arr.inject { |result, item| result + (item / sum - 0.2) ** 2} ) # 0.4473023458029664
the result:
0.42948006253339877 != 0.4473023458029664
why ??
Upvotes: 1
Views: 141
Reputation: 146053
Because in the second case you don't do any operations on the first element but immediately put it into the result.
In the first computation, the explicit loop, you begin with an external sum variable initialized to zero.
To be an equivalent of the later (inject) code, the coded loop would need to look like this:
tmp = arr[0]
arr[1..-1].each do |pwr|
...
Upvotes: 4
Reputation: 139840
You're not specifying a starting value for inject
, so it uses the first value as the accumulator instead of 0
in your explicit code.
Do this instead:
arr.inject(0) { ... }
Upvotes: 4
Reputation: 726
What you want is:
arr.inject(0){ |result, item| result + (item / sum - 0.2) ** 2}
Upvotes: 3