Python部分谐波

时间:2015-09-05 23:30:08

标签: python

有人可以帮助检查为什么结果总是一个,让我知道我做错了什么?感谢

正确的结果应该是: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))

2 个答案:

答案 0 :(得分:2)

它可以在python 3上正常工作,但不能在python 2

中工作
>>> 1/2
0

这意味着你只需要添加一个零。您需要将分子或分母更改为浮点数,例如1/2.0,请将代码更改为

result += 1.0 / n

请参阅Pep 238,了解它在python 3中的更改原因。

btw浮点数不能代表所有分数,所以如果你只是添加分数,你可以使用Fraction类,例如。

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

答案 1 :(得分:0)

作为替代方案,要强制Python 2按预期执行除法(而不是整数除法),请添加:

topic_count <- df %>% group_by(Topic) %>% summarise(total=n())
user_count <- df %>% group_by(Topic, User) %>% summarise(cnt=n())

user_count %>%
    left_join(topic_count, by="Topic") %>%
    mutate(Importance=cnt/total) %>%
    select(-cnt, -total) # Drop obsolete columns

##   Topic User Importance
## 1 A       U1       0.75
## 2 A       U2       0.25
## 3 B       U1       0.50
## 4 B       U2       0.50