Sum the series to 'n'

时间:2018-03-13 15:11:02

标签: python series

Just trying to sum the series 1/(1 + 3n) for a given n. I've used the code below and get an "invalid syntax" message, but I can't understand why as other examples seem to do the same. Returning a value rounded to two decimal places

def series_sum(n):
    ans = 0
    for i in range(0, n+1):
        ans = ans + (1/(1+3i))
    return round(ans, 2)

2 个答案:

答案 0 :(得分:1)

只是这样做:

def series_sum(n):
    ans = 0
    for i in range(0, n+1):
        ans = ans + (1.0/(1.0+3.0*i))
    return round(ans, 2)

你应该使用*进行乘法,并在你的等式中浮动,以使你的结果成为浮点数。

缩进在python中也很重要。

答案 1 :(得分:1)

以下是代码的标识更正版本,显示错误

$ cat d.py 
def series_sum(n):
    ans = 0
    for i in range(0, n+1):
        ans = ans + (1/(1+3i))
    return round(ans, 2)

$ pyflakes d.py
d.py:4:28: invalid syntax
        ans = ans + (1/(1+3i))
                           ^        

以下是如何修复它

def series_sum(n):
    ans = 0
    for i in range(0, n+1):
        ans = ans + (1/(1+3*i))
    return round(ans, 2)

写作" 3i"是" 3次i"的有效语法所以使用*运算符乘以

$ python
Python 3.5.3 (default, Jun 22 2017, 11:09:36) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from d import series_sum
>>> series_sum(2)
1.39