1

Here's the equation

x + x^2/2 + x^3/3 +.... x^n/n

How will I find the sum of this series? x is a constant term to be entered by user and n which is power is also based on user!

I made this program but it's not working properly.. Have a look -

n=input("Enter power ")
x=input("Enter value of x")
i=0
while i<n:
    c=n-1
    res=(x**(n-c))/(n-(c))
    print res
    i=i+1

So how do we make it? Thanks a ton for your help!

Update : The answers helped me and now the program is working as it should! This was my first time using Stackoverflow! Thanks to everyone for this.

Ins
  • 13
  • 4

3 Answers3

2

Something like this for your loop? Tried to keep it simple.

n = input("Enter power ")
x = float(input("Enter value of x"))

ans = 0
for i in range(1, n+1):
    ans += x**i/i

print(ans)

See zev's answer regarding floats

perfect5th
  • 1,992
  • 1
  • 17
  • 18
2

You're not adding the terms together.

Also, you need to be careful that you use float division when x is an integer. See this thread.

Here's a working implementation:

n = input("Enter power: ")
x = input("Enter value of x: ")
result = 0
for i in range(1, n+1):
    result += (x**i) / float(i)
print result
Community
  • 1
  • 1
Zev Chonoles
  • 1,063
  • 9
  • 13
0

Issue with your program is that your are not adding the sum. See: res=(x**(n-c))/(n-(c)). Instead do:

res += (x**(n-c))/(n-(c))

You may also achieve it by using in-built sum, map and lambda functions as:

y = 5  # or any of your number
sum(map(lambda x: (y**x)/float(x), xrange(1, y)))
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • 1
    Thanks for your efforts! This seems really nice but I am not supposed to use the built in functions! :/ Btw Still Thanks a ton for your efforts! – Ins Aug 25 '16 at 18:29