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+...
2 Answers 2
A few issues with your current solution:
Your exponentiation operator should be
**not^which is XOR.You should start
rangefrom 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
answered Jul 21, 2018 at 15:13
Moses Koledoye
78.8k8 gold badges140 silver badges141 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
M.Papapetros
Thank you very much. Is there a way to solve this problem without the use of "for" or "while"?
Moses Koledoye
@M.Papapetros My (power) series maths is a bit rusty. Try asking on math.stackexchange.com if there's an arithmetic reduction for your series.
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
answered Jul 21, 2018 at 15:11
Bal Krishna Jha
7,6293 gold badges45 silver badges48 bronze badges
Comments
lang-py
1.range(1,n,2)?