Ryan Glass - 10 months ago 162

Ruby Question

I am trying to write a program that calculates a Harmonic series from a whole number. Such as 5 and calculates it until it reaches that argument.

So essentially it looks like:

h1: 1 / 1

h2: 3 / 2

h3: 11 / 6

h4: 25 / 12

h5: 137 / 60

This is what I have.

my question is, is there a formula that will calculate a harmonic series in ruby?

`class Fraction`

attr_accessor :numerator, :denominator

def initialize(n, d)

@numerator = n

@denominator = d

end

def +(rhs)

n = @numerator*rhs.denominator + @denominator*rhs.numerator

d = @denominator*rhs.denominator

n, d = reduce(n, d)

return Fraction.new(n, d)

end

def print

puts "#{@numerator} / #{@denominator}"

end

def reduce(n, d)

r = gcd(n, d)

return n / r, d / r

end

def gcd(a, b)

if a % b == 0

return b

else

return gcd(b, a % b)

end

end

private :reduce, :gcd

end

Answer Source

The harmonic series isn't implemented in Ruby standard library, but Rational is :

```
def harmonic_sum(n)
(1..n).inject(Rational(0,1)) {|r, i| r + Rational(1,i) }
end
puts harmonic_sum(5)
#=> 137/60
puts harmonic_sum(50)
#=> 13943237577224054960759/3099044504245996706400
puts harmonic_sum(10_000).to_f
#=> 9.787606036044382
```

NOTE: Your code is fine BTW. Here are some slight modifications and a few TODOS ;)

```
class Fraction
attr_reader :numerator, :denominator
def initialize(n, d)
@numerator = n
@denominator = d
end
def to_f
numerator.to_f/denominator
end
#TODO: Add *
#TODO: Define - and / with + and *
#TODO: Check that rhs is a Fraction, convert self to float otherwise.
def +(rhs)
n = @numerator*rhs.denominator + @denominator*rhs.numerator
d = @denominator*rhs.denominator
n, d = reduce(n, d)
return Fraction.new(n, d)
end
def to_s
"#{@numerator} / #{@denominator}"
end
private
def reduce(n, d)
r = gcd(n, d)
return n / r, d / r
end
def gcd(a, b)
if a % b == 0
return b
else
return gcd(b, a % b)
end
end
end
def harmonic_sum(n)
(1..n).inject(Fraction.new(0,1)) {|r, i| r + Fraction.new(1,i) }
end
puts harmonic_sum(100)
#=> 14466636279520351160221518043104131447711 / 2788815009188499086581352357412492142272
```