0

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+...

asked Jul 21, 2018 at 15:02
2
  • @VasilisG. Why? Default step is 1. Commented Jul 21, 2018 at 15:05
  • range(1,n,2)? Commented Jul 21, 2018 at 15:06

2 Answers 2

3

A few issues with your current solution:

  1. Your exponentiation operator should be ** not ^ which is XOR.

  2. You should start range from 0 not 1 (then first multiplier is -1**0 = 1)

  3. 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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much. Is there a way to solve this problem without the use of "for" or "while"?
@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.
0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.