Reputation: 49
I have this Python function:
def main(n,x):
g=0
for i in range(1,n):
g+=((-1)^i)*(x^(2*i+1))/(2*i+1)
return g
print main(3,2)
and the output is -6, when I think it should be 86/15. Where is my mistake? I want to find the n-value of x-(x^3)/3+(x^5)/5+...
Upvotes: 0
Views: 98
Reputation: 7206
If you want your answer in fraction you can use:
from fractions import Fraction
def main(n,x):
g=0
for i in range(n):
g+=Fraction(((-1)**i)*(x**(2*i+1)),(2*i+1))
return g
print main(3,2)
It gives output:
86/15
Upvotes: 0
Reputation: 78536
A few issues with your current solution:
Your exponentiation operator should be **
not ^
which is XOR.
You should start range
from 0 not 1 (then first multiplier is -1**0 = 1
)
Change one of the numbers in the division to float, to avoid integer division in Python 2.
def main(n, x):
g = 0
for i in range(n):
g += ((-1)**i) * (x**(2*i+1))/float(2*i+1)
return g
Upvotes: 3