rabbit
rabbit

Reputation: 73

Python Partial Harmonics

Could someone help check why the result is always one and let me know what I did wrong? Thanks

Correct result should be: 1/1 + 1/2 + 1/3 == 1.83333333333.

x = int(input("Enter n: "))
assert x > 0, "n must be greater than zero!"

def one_over_n(x):

    result = 0

    for n in range(x):
        n += 1
        result += 1 / n
    return result
r = one_over_n(x)
print("one_over_n( {0:d} ): {1:f}" .format(x, r))

Upvotes: 0

Views: 73

Answers (2)

Maksim Yegorov
Maksim Yegorov

Reputation: 99

As an alternative, to force Python 2 perform division as you expect (rather than integer division), add:

from __future__ import division

Upvotes: 0

Anurag Uniyal
Anurag Uniyal

Reputation: 88827

It will work correctly on python 3, but not in python 2

>>> 1/2
0

That means you are just adding zeroes, to one. You will need to change either numerator or denominator to a float number e.g. 1/2.0, so change your code to

result += 1.0 / n

See Pep 238 to see why it was changed in python 3.

btw floating point numbers can't represent all fractions, so if you are just adding fractions, you can use Fraction class e.g.

>>> from fractions import Fraction as F
>>> F(1,1) + F(1,2) + F(1,3)
Fraction(11, 6)

Upvotes: 2

Related Questions