0

I am not understanding why my code isn't looping, for any input I give I get the result of "1.00"

I feel like I am being silly and missing something very obvious.

This series is shown in other places most often as 1/3n+1

But if series_sum(1) = "1.00"

then 3+1 = 4 giving you 1/4 to add to your sum for input of 1 which doesn't make sense

def series_sum(n)
  sum = 0
  if n == 0
    return "0.00"
  else
    for i in 1..n 
      sum += 1/(1+(3*(i-1)))
    end
  end

  return "%.2f" % sum.to_s

end

for series_sum(1) should be "1.00" series_sum(2) should be "1.25" series_sum(3) should be "1.39" etc

My code gives "1.00" for any input

Why won't this code run the loop and perform the sum?

iGian
  • 11,023
  • 3
  • 21
  • 36
Mary Lang
  • 31
  • 1
  • 5
  • 1
    When dividing, if the numerator or denominator is a float, the result will be a float; else it will be an integer (with the remainder being discarded). Integer division: `4/2 #=> 2; 4/3 #=> 1; 1/2 #=> 0`. Float division `4/3.0 #=> 1.33...; 1.0/2 #=> 0.5; 1.to_f/2 #=> 0.5`. A more complex example: `3/(2/(1+4).to_f) = 3/(2/5.0) = 3/0.4 #=> 7.5`. You can alternatively write `1.fdiv(3) #=> 0.5`. See [Numeric#fdiv](http://ruby-doc.org/core-2.5.1/Numeric.html#method-i-fdiv). – Cary Swoveland Jun 26 '19 at 01:12
  • 2
    Float division, could also be fixed changing this line: `sum += 1.0/(1+(3*(i-1)))`. Note the numerator: `1.0`. Side note, instead of `for` loop, use a more Rubyish: `(1..n).each do |i|` – iGian Jun 26 '19 at 06:07

1 Answers1

2

When you have expression like z = x/y, in ruby it does specify type for output based on operand provided for division. If x & y both are integer, output calculated is also integer and float value is removed.

So to obtain output as float, you need to have one operand at least as float value which can be found using to_f on variable. Here you need to change only,

- sum += 1/(1+(3*(i-1)))
+ sum += 1.0/(1+(3*(i-1)))
ray
  • 5,454
  • 1
  • 18
  • 40