Here is the question my teacher gave us:
Write a program to find the sum of the following series (accept values of x and n from user). Use functions of the math library like math.pow and math.factorial: 1 x/1! x2/2! ……….xn/n!
This is the code I've come up with. I calculated it on paper with simple numbers and there's clearly some logic errors because I can't get a correct answer. I think I've been looking at it for too long to really grasp the issue, so I could use some help.
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
for i in range (n):
power = math.pow(x,i)
ans = 1 (power / math.factorial(i))
print(ans)
Note: This is an entry level class, so if there's an easier way to do this with a specific function or something I can't really use it because I haven't been taught it yet, although appreciate any input!
CodePudding user response:
I believe the following will work for you:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
ans = 1
for i in range (1,n 1):
power = math.pow(x,i)
ans = (power / math.factorial(i))
print(ans)
We start the ans variable at 1 and we add the new term to ans through each iteration of the loop. Note that x =n
is the same as x=x n
for integers.
I also changed the range that your loop is going through, since you start at 1 and go up to n, rather than starting at 0 and going to n-1.
Output:
Input x: 2
Input n: 5
7.266666666666667
For people familiar with the mathematical constant e:
Input x: 1
Input n: 15
2.718281828458995
CodePudding user response:
Your ans
only includes (the 1 and) the latest term. You should instead Initialize it before the loop and then add all the terms to it. The first term 1 doesn't deserve ugly special treatment, so I compute it like all the others instead:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
ans = 0
for i in range(n 1):
ans = math.pow(x, i) / math.factorial(i)
print(ans)
And a preview how you'll likely soon be taught/allowed to write it:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
print(sum(math.pow(x, i) / math.factorial(i)
for i in range(n 1)))
CodePudding user response:
I would not recommend using those functions. There are better ways to do it that are within the grasp of entry level programmers.
Here's what I recommend you try:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
sum = 1
term = 1.0
for i in range (1,n 1):
term *= x/i
sum = term
print(sum)
You don't need those functions. They're inefficient for this case.